this keyword points to object's own instance. You can only use it inside the class body. Following are the usage of this keyword-
Let's understand the above points with the help of examples.
If instance variables and method parameters have the same name, then this keyword helps in differentiating between instance variables and method parameters.
public class Employee { int id; String name; int salary; public Employee(int id, String name, int salary) { id=id; name=name; salary=salary; } void show() { System.out.println(id+" "+name+" "+salary); } public static void main(String args[]) { Employee emp1 = new Employee(1, "Govind", 10000); emp1.show(); } }
Output
0 null 0
As you can see method parameters and instance variables are having same name. So, this keyword is used to differentiate instance variable from method parameters.
public class Employee { int id; String name; int salary; public Employee(int id, String name, int salary) { this.id=id; this.name=name; this.salary=salary; } void show() { System.out.println(id+" "+name+" "+salary); } public static void main(String args[]) { Employee emp1 = new Employee(1, "Govind", 10000); emp1.show(); } }
Output
1 Govind 10000
You can call instance method of a class with or without using this keyword.
public class X { public void show() { System.out.println("Method is called using this keyword."); } public void display() { this.show(); } public static void main(String args[]) { X x = new X(); x.display(); } }
Output
Method is called using this keyword.
this keyword allows us calling of another constructor of the same class. If you are using this, then it must appear at the beginning of the code block of the constructor.
public class X { private int a; public X() { this(10); } public X(int a) { this.a = a; } public void display() { System.out.println(a); } public static void main(String args[]) { X x = new X(); x.display(); } }
Output
10
Note- You can call any constructor from within a constructor. For example, you can call default constructor from parameterized constructor and call parameterized constructor from default constructor.
If you want to return this keyword from a method, then return type of the method must be a class type.
public class X { public X getX() { return this; } public void display() { System.out.println("I am a display() function."); } public static void main(String args[]) { new X().getX().display(); } }
Output
I am a display() function.