this keyword in java
The "this"
keyword is used to refer to the current instance of a class.
Example:
- public class Employee
- {
- int age;
- public Employee(int age)
- {
- this.age = age;
- }
- private void displayEmployee(){
- System.out.println("Employee's age : " + this.age);
- }
- public void printEmployee(){
- this.displayEmployee();
- }
- }
public class Employee { int age; public Employee(int age) { this.age = age; } private void displayEmployee(){ System.out.println("Employee's age : " + this.age); } public void printEmployee(){ this.displayEmployee(); } }
this.age accesses a variable of the current instance of Employee class.
this.displayEmployee() invokes a method of the current instance of the Employee class.
Note:
"this"
keyword is optional to use but it increases the code readability.In some cases where local variable and instance variable name are same,
"this"
keyword is mandatory to refer to the current instance’s variable otherwise local variable gets the precedence.
Example:
- public class Employee
- {
- int age;
- public Employee(int age)
- {
- age = age;
- }
- public void displayEmployee(){
- System.out.println("Employee's age : " + age);
- }
- }
public class Employee { int age; public Employee(int age) { age = age; } public void displayEmployee(){ System.out.println("Employee's age : " + age); } }
In the above example, since we are not using 'this'
in the constructor,
In assignment age=age, both left and right side ‘age’ are considered as local variable and hence no value will be assigned to instance variable.
- public class Employee
- {
- int age;
- public Employee(int age)
- {
- this.age = age;
- }
- private void displayEmployee(){
- System.out.println("Employee's age : " + this.age);
- }
- }
public class Employee { int age; public Employee(int age) { this.age = age; } private void displayEmployee(){ System.out.println("Employee's age : " + this.age); } }
In the above example, since we have used 'this'
in the constructor,
In assignment age=age, left side ‘age’ accessed using 'this'
refers to instance variable and right side ‘age‘ refers to local variable and hence local variable value will be assigned to instance variable.
So 'this'
keyword always refers to the current instance of the class and should be used when a reference will be ambiguous as stated above.