Wednesday, July 23, 2014

this keyword in Java

This keyword:-

1) this keyword represent current instance of class.

2) You can synchronize on this in synchronized block in Java

3) this keyword can be used to call overloaded constructor in java. if used than it must be first statement in constructor this() will call no argument constructor and this(parameter) will call one argument constructor with appropriate parameter. here is an example of using this() for constructor chaining:
4) this can be used to return object. this is a valid return value. here is an example of using as return value.
public Loan getLoan(){
 return this;
}

5) this can be used to refer static members in Java as well but its discouraged and as per best practices
this should be used on non static reference.

6) "this" keyword can not be used in static context i.e. inside static methods or static initializer block.
if use this inside static context you will get compilation error as shown in below example:

public static void main(String args){
       this.toString{}; //compilation error: non static variable this can not be used in static context
  }

this keyword refers to the object that is currently executing. It is useful for a method to reference instance variables relative to the this keyword.
Example 1 : Program that creates class Square and assigns values to variables using constructor and this keyword
class Square
{
       int height;
       int width;

         Square(int height, int width)
         {
               // Note that constructor variable and instance variable names are same
               
                this.height = height; 
                this.width = width;
          }
}

class ImplSquare
{
     public static void main(String args[])
     {
             Square sObj1 = new Square(2,3);             

             System.out.println("Variable values of object : ");
             System.out.println("Object height =  " + sObj1.height);
             System.out.println("Object width = " + sObj1.width);
      }
}


Output

Variable values of object : 
Object height =  0
Object width =  0

As in above example you can note that constructor variable and instance variable names are same. But using this keyword compiler can differentiates constructor variables and instance variables.

  1. this keyword can be used to refer current class instance variable.
  2. this() can be used to invoke current class constructor.
  3. this keyword can be used to invoke current class method (implicitly)
  4. this can be passed as an argument in the method call.
  5. this can be passed as argument in the constructor call.
  6. this keyword can also be used to return the current class instance.
  7. This keyword can never static it make only dynamic values which are change .


No comments:

Post a Comment