Monday, April 20, 2015

this keyword in java

Many beginners feel difficult to understand 'this' keyword in java and can't implement it correctly.So here are the some usage of 'this' keyword in java which will help you to understand where and how to implement 'this' keyword.

Usage of java this keyword in Java.

1. this keyword can be used to refer current class instance variable.
 
   Example:-
 
   class Person{  
    int age;//instance variable  
    String name;//instance variable  
      
   Person(int age,String name){  
    this.id = id;  
    this.name = name;  
    }  
    void display(){
       System.out.println(id+" "+name);
     }  
    public static void main(String args[])
  {  
    Person p = new Person(23,"Sanam");  
    p.display();  
    }  
  }

   Output:23 Sanam
     
2. this() can be used to invoke current class constructor.

   class Person{  
    int age;  
    String name;  
    Person()
    {
    System.out.println("default constructor is invoked");
    }  
      
    Person(int id,String name){  
    this ();//it is used to invoked current class constructor.  
    this.age = age;  
    this.name = name;  
    }  
    void display()
    {
    System.out.println(id+" "+name);
    }  
      
    public static void main(String args[])
    {  
    Person p = new Person(23,"Sanam");  
    p.display();    
   }  
}  
Output:
       default constructor is invoked
       23 Sanam
     

3. this keyword can be used to invoke current class method (implicitly).

  class Person{  
  void display()
  {  
  System.out.println("method is invoked");  
  }  
  void call()
  {  
  this.m();//no need because compiler does it for you.  
  }  
  public static void main(String args[])
  {  
  Person p = new Person();  
  p.call();  
  }  
}  
Output:- method is invoked

Note:- There is no need to add this keyword to invoke method compiler will add 'this' keyword automatically.Even if you delete this keyword(this.display) program will run.

4. this can be passed as an argument in the method call.

  class P{  
  void m(P obj){  
  System.out.println("method is invoked");  
  }  
  void call(){  
  m(this);  
  }  
    
  public static void main(String args[]){  
  P s = new P();  
  s.call();  
  }  

Output:method is invoked

5. this keyword can also be used to return the current class instance(object).

class A{  
void p(){  
System.out.println(this);//prints same reference ID  
}  
  
public static void main(String args[]){  
A obj=new A();  
System.out.println(obj);//prints the reference ID  
  
obj.p();  
}  
}  

Output:A5@22b3ea59
       A5@22b3ea59

No comments:

Post a Comment