Sunday, 10 July 2016

"this" keyword in Java

"this" keyword can be used to represent current object or instance of any class in Java. It can also call constructor of same class and used to call overloaded constructor.

Usage of java this keyword
1. "this" keyword can be used to refer current class instance variable.
"this" keyword can be used to resolve the ambiguity between the instance variable and method/constructor parameter.
class Test { 
     int id

     Test(int id){ 
           this.id = id
     }
}

2. "this()" can be used to invoke current class constructor.

3. "this" keyword can be used to invoke current class method (implicitly).
class Test { 
     void method1() { 
           System.out.println("method is invoked"); 
     } 
     void method2() { 
           this.method1();//no need because compiler does it for you. 
     } 
     void method3() { 
           method1();
           //complier will add this to invoke method1() method as this.method1() 
     } 
     public static void main(String args[]) { 
           Test test = new Test(); 
           test.method2();
           test.method3();
     } 
}

4. "this" can be passed as an argument in the method/constructor call since it represent current object of class.

5. "this" can be used to return current class instance.
public MyClass getClassInstance(){
     return this;
     //"this" keyword cannot be used in static context i.e. inside static methods or static initializer block.
}

6. We can synchronize on this in synchronized block in Java
synchronized(this){
     //this synchronized block will be locked on current instance
}


Note:
1. "this" is a final variable in Java and you cannot assign value to this.
this= new MyClass (); //cannot assign value to final variable : this

2. If use this inside static context you will get compilation error.
public static void main(String args){
     this.toString{}; //compilation error: non static variable this cannot be used in static context
}

3. Inside a constructor, the call to this(...) must be the first instruction.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...