Sep 8, 2013

this reference in Java

this reference-

this keyword in java programming is used to refer the current class object. this keyword is used when we want to call methods without creating object. this reference stores in the memory when an object of the current class is instantiated. We can say "this" is a special keyword in java programming which is used to refer current class object or instance of any class. By using this keyword we can call methods of current class as well as constructor. Let us see use of this reference in java and its interesting example.
  • this is the keyword of java.
  • this reference holds the address of current class's object.
  • this reference can not be used inside any static context.
  • this reference can be used inside any non-static context.
  • this reference refers to the current class object.
  • this reference stores in the memory how many times object of the class is instantiated.
this  reference is used to call a non-static method of the current class without using the object. for example- if there is a method names "getdata", we can call this method as follows-
        this.getdata();

here, this keyword is holding the reference of the current class object so it can also call the any method of the same class. however we can also call the methods without this reference such as-
      getdata();
this reference is very useful in some cases like-

        class This1 
{
int k=200;
void m1()
{
int k=100;
System.out.println("this="+this);
System.out.println(k);
System.out.println(this.k);
}
public static void main(String[] args) 
{
This1 d1=new This1();
This1 d2=new This1();
This1 d3=new This1();
System.out.println("d1="+d1);
System.out.println("d2="+d2);
System.out.println("d3="+d3);
d1.m1();
d2.m1();
d3.m1();

}
}

Output-


this reference in java

It completes the discussion of this reference.we will discuss about this-call later. For more study about this reference please follow these links-