There can be a lot of usage of java this keyword. In java, this is a reference variable that refers to the current object.


Usage of java this keyword

  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.

Note: If you are beginner to java, lookup only two usage of this keyword.


Example of without this keyword

class Student1{  
    int id;  
    String name;        
    Student1(int id,String name){  
    id = id;  
    name = name;  
    }  
    void display(){System.out.println(id+" "+name);}    
    public static void main(String args[]){  
    Student1 s1 = new Student1(101,"Ramu");  
    Student1 s2 = new Student1(102,"Ramesh");  
    s1.display();  
    s2.display();  
    }  
}  

Example of with this keyword

class Student1
{  
int id;  
String name;  
Student1(int id,String name)
{  
this.id = id;  
this.name = name;  
}  
void display()
{
System.out.println(id+" "+name);
}  
public static void main(String args[]){  
Student1 s1 = new Student11(101,"veeru");  
Student1 s2 = new Student11(102,"sunny");  
s1.display();  
s2.display();  
}  
}  

Output: 101 veeru
        102 sunny

Where this keyword is not required

class Student1
{  
int id;  
String name;  
Student1(int i,String n){  
this.id = i;  
this.name = n;  
}  
void display(){System.out.println(id+" "+name);}  
public static void main(String args[]){  
Student1 s1 = new Student11(101,"Ramu");  
Student1 s2 = new Student11(102,"Ramesh");  
s1.display();  
s2.display();  
}  
}  
Output: 101 Ramu
        102 Ramesh

News Walls


Copyrights © 2016. All Rights Reserved to Learn Computers Home, India. //Site Designed.