by Dinesh Thakur Category: Classes

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();
            System.out.println("Area of First Rectangle : "+ firstRect.area());
            System.out.println("Area of Second Rectangle : "+secondRect.area());

Object Reference this in Java

About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.

Search Content

Popular Article