Saturday, March 27, 2010

"this" Keyword in Java








public class ThisKeywordDemo {

     int a;
     int b;

     /**
      * This main method is written to test our demo
      *
      * @param args      */
    public static void main(String[] args) {
          // Declaring a object "result" to store sum of two objects.
         ThisKeywordDemo result = new ThisKeywordDemo();

         // Declaring and Initializing obj1
        ThisKeywordDemo obj1 = new ThisKeywordDemo();
        obj1.a = 5;
       obj1.b = 2;

        // Declaring and Initializing obj2
       ThisKeywordDemo obj2 = new ThisKeywordDemo();
       obj2.a = 3;


       obj2.b = 4;

       /*  == First Call of add method ==
        * Calling add method to add obj1 and obj2
        * Where "obj1" will be accessed by "this" keyword and "obj2" is passed as parameter
        */




        result = obj1.add(obj2);
       System.out.println("=========== Sum of Obj1 and Obj2 ===========");
       System.out.println("Result : a = " + result.a + " b : " + result.b);       
      // Declaring and Initializing obj3
      ThisKeywordDemo obj3 = new ThisKeywordDemo();
      obj3.a = 25;
      obj3.b = 21;
    
     /* == Second Call of add method ==
      * Calling add method to add obj1 and obj3
      * Where "obj3" will be accessed by "this" keyword and "obj2" is passed as parameter
      * -- Here parameter is same in both calls of add method..

      * only invoking object is changed,which will be accessed by "this" Keyword.
      */
      result = obj3.add(obj2);
      System.out.println("================ Sum of Obj2 and Obj3 ===========");
      System.out.println("Result : a = " + result.a + " b : " + result.b);
}

/*
* This method is used to add two objects of ThisKeywordDemo class.
* e.g
* Input:


*          obj1 => obj1.a = 5, obj1.b= 2
*          obj2 => obj2.a = 3, obj2.b= 4
* Output:
*          obj3 => obj3.a = 8, obj3.b = 6
*/

     public ThisKeywordDemo add(ThisKeywordDemo thisKeywordDemo) {

          ThisKeywordDemo temp = new ThisKeywordDemo();
          temp.a = this.a + thisKeywordDemo.a;
          temp.b = this.b + thisKeywordDemo.b;          return temp;
     }
}