Sunday, 1 November 2015

WHAT IS A THIS KEYWORD AND WHY IT IS USED FOR IN JAVA..??




WHAT IS A THIS KEYWORD:


       ‘THIS’ keyword is generally referred to current class instance variable . 


        There are many reasons for us to use THIS KEYWORD


        Let me list out one by one


    IT IS USED TO REFER  INSTANCE VARIABLE AND METHODS.


       When an instance variable name is same as the parameter name then THIS keyword can be used.

If you want to know what an instance variable is please refer this


    Consider the example..


    Class classname

   {

int myname=0;
     int yourname=0;

       public void add(int myname, int yourname )

         {

           myname = myname;

           yourname = yourname;

           System.out.println(“the value of the variable is  + myname ) ;

           System.out.println(“the value of the variable is  + yourname ) ;

         }
     public static void main(String args[])

         {

        classname classobj = new classobj;

       Classobj.add(3,3);

      }

    }


  Output:


     The value of the variable is 0.


  EXPLANATION:


       Note the value we are passing to the parameter is  3 , 3 and the name of the argument we gave is myname and yourname


      The instance variables declared are myname and yourname


      In this case we want to assign the instance variable with the values of the parameter.


     So, if we simply say like myname  = myname and

  yourname = yourname then, pity compiler will get confused.. “Arey developer ..you can’t even tell to whether its an instance variable or the variable in the argument and you are assigning it just like that.. “ is what the compiler is scolding the developer.


     So, developer has decided a thing ..that is to use ‘THIS’ keyword.


HOW DOES THE THIS KEYWORD ACTUALLY HELPS THE COMPILER AND THE DEVELOEPR??


When ‘this’ keyword comes into being… the code will look like



 Class classname
     {
   int myname=0;
  int yourname=0;
    public void add(int myname, int yourname )

     {

           this. myname = myname;

           this.yourname = yourname;

           System.out.println(“the value of the variable is  + myname ) ;

           System.out.println(“the value of the variable is  + yourname ) ;

 }
     public static void main(String args[])

       {

         classname classobj = new classobj;

         classobj.add(3,3);

      }

}


     OUTPUT:


      3

      3


EXPLANATION:


       Note the output here is 3 and 3 and not 0 because hurrahhh the compiler is happy for not making him go mad like before.


     We have used ,

              this. myname = myname;

              this.yourname = yourname; 


     When we have used ‘this’ then the variable which is near ‘this’ keyword actually refers to ‘instance variable’ and the variable which is to the right of ‘= ‘  is the parameter variable . So we are telling the compiler that assign the value of myname and yourname which we have got from the parameter to the instance variable.


        So myname(instance variable) = 3(value that parameter has received)

Yourname =3



NOTE : When the name of the instance variable is not same as the parameter variable then THIS keyword is not necessary


EXAMPLE:



     Class classname
      {

  int myname=0;
       int yourname=0;

        public void add(int hai, int bye )

           {

                myname = hai;

                yourname = bye;

                System.out.println(“the value of the variable is  + myname ) ;

                System.out.println(“the value of the variable is  + yourname ) ;



             }

       public static void main(String args[])

         {

            classname classobj = new classobj;

            classobj.add(3,3);

         }

    }


      Here the instance variable is assigned directly with the parameter variable.


  THIS CAN BE USED TO CALL THE CURRENT CLASS CONSTRUCTOR 


         Uhhff… “THIS” keyword is performing loads and so we have to learn its functionality completely else it will get angry.. yes of course its helping us in many ways and we must spend some time reading it..So have patience and continue reading…


           Lets jump directly into the example


     Class Classname

          {

         Classname()

             {

                System.out.println(“Constructor is invoked”);

             }

      int myname=0;
      int yourname=0;

      Classname(int hai, int bye )

          {

          this ( );

          myname = hai;

          yourname = bye;

          System.out.println(“the value of the variable is  + myname ) ;

          System.out.println(“the value of the variable is  + yourname ) ;

         }
           public static void main(String args[])

           {

           Classname classobj = new classobj(3,3);

            }

       }



    OUTPUT:


         Constructor is invoked

         the value of the variable is  3

         the value of the variable is  3



  EXPLANATION : 


       If you don’t know what a constructor actually is , please refer this constructors in java . As of now the method which has the same name as the class name is called constructor and it will get automatically invoked when the object creation is done. ie. when we use the ‘new keyword’


          So we need not call the constructor ie. Classname ( ) explicitely.


          Here in the above case the constructor Classname(int hai, int bye ) is invoked as the datatype matches and it will start executing it but as soon as it sees the keyword this( ) , then the default constructor will get invoked.. and so the output “Constructor is invoked” will get printed first and then other constructors will get executed  .



   THIS KEYWORD CAN BE USED TO CALL CURRENT CLASS METHOD:


     Class classname

         {

          Void add ( )

               {

                      System.out.println(“the method is called” );

                }



           Void sub ( )

             {

             System.out.println(“the method is called” );

             add( );                                                                           
             this.add( );  //  compiler calls by adding ‘this’ keyword.

              }

            Public static void main(String args[] )

             {

              classname cn= new classname( );

              cn.sub( );
            } 
}                                                                                                                                                                                                                                                                                                                                                           
Even if we don’t use the ‘this’ keyword , it will be automatically be added by the compiler while calling the methods of the same class.



   THIS KEYWORD CAN BE USED TO PASS AS AN ARGUMENT


       class SecondClass
            {  

          FirstClass obj;  

          SecondClass(SecondClass obj)
             {  

                 this.obj=obj;  

             }  

       void display()
            {  

         System.out.println(obj.data);//using data member of A4 class  

            }  

     }  

  

class FirstClass
     {  

        int data=10;  

        FirstClass()
          {  

             SecondClass second=new SecondClass(this);  

             second.display();  

            }  

          public static void main(String args[])
           {  

              FirstClass a=new FirstClass();  

            }  

        }  


      Here, initially the object creation is done for the FirstClass and so the constructor of the FirstClass will be called automatically.


       Then we are creating an object for the second class inside the first class and inside bracket we are using ‘this’ keyword meaning we are passing a copy of FirstClass to the constructor of the SecondClass.


      Default constructor gets invoked for the secondclass and if a class passes something ..then someone must be there to receive it ..but we must mention that receiver belongs to that class only so, inside the  Constructor of the second class we must specify “SecondClass obj” where obj is the name of the receiver because sender won’t get satisfied if the name of the sender is not mentioned and won’t even send the stuffs. 

       FirstClass reference must be created for holding the copy that is sent by the FirstClass.So, a reference variable " obj" is created for the FirstClass and using that reference variable any method and variables can be accessed from the second class


          So in a similar way “obj.data” meaning data variable of the second class is created and variable is accessed.



  THIS REFERS TO CURRENT CLASS INSTANCE:


      Class hai
     {

        void hello ( )

          {

            System.out.println(“printed using this” +this);
           }

            public static void main(String args[])

             {

                  hai bye =new hai  ( );

                  bye.hello ( );

                  System.out.println(“printed using object”+bye);

             }
      }

   OUTPUT: 


     printed using this  123@r345623

     printed using bye 123@r345623


  EXPLANATION:


     Note that both have same output because object holds the memory address and so, “this”

    “This” keyword also refers to the memory location . It refers to current class instance meaning ‘object’ and so it is printing the same value.


CONCLUSION:


   So…I know it’s a really long post but clap your hands and say a big hurrahhhhh if you have understood the very basic and important keyword in java. Please leave your comments below , hit like button and support my work ..!! Suggestions are always  welcomed. If you want to request for the post you wish to read.. then tap a mail to anushaks94@gmail.com . Hope you understood the concepts better…Have a nice day :)

No comments :

Post a Comment