by Dinesh Thakur

Whenever the objects of a class are instantiated, each object will have its own copy of instance variable(s), however all objects share only one copy of each instance method of the class. So the question arises how does a method know for which object the method was called. In other words, how does a method know which instance variable it should get/set or use to calculate a value? This is possible using a special object reference variable named this. When a method starts executing, the JVM sets the object reference this to refer to the object for which the method has been invoked. The compiler uses this implicitly when your method refers to an instance variable of the class. So any instance variable referred to by a method is considered to this. instanceVariable.

class Rectangle

{
       int length;
       int breadth;
       void setData(int length,int breadth)
       {
         this.length = length;
         this.breadth = breadth;
       }
       int area()
       {
         int rectArea;
         rectArea = length * breadth;
         return rectArea;
       }
}
     class ObjectReferencethis
{
           public static void main(String[] args)
       {
            Rectangle firstRect = new Rectangle();
            Rectangle secondRect = new Rectangle();
            firstRect.setData(5,6);
            System.out.println("Area of First Rectangle : "+ firstRect.area());
            secondRect.setData(10,20);
            System.out.println("Area of Second Rectangle : "+secondRect.area());
       }
}

Object Reference this in Java