The this keyword in Java is a reference to the current object of a class. It is commonly used to access instance variables, invoke methods of the current object, and resolve naming conflicts between instance variables and method parameters.
Key Points: • this refers to the current object instance. • It is used to distinguish instance variables from local variables or method parameters with the same name. • It can be used to invoke another constructor within the same class using this(). • It can be passed as an argument to methods or constructors. • It can be returned from a method to return the current object.
Example: When a constructor parameter has the same name as an instance variable, the this keyword helps differentiate between them.
Code Example:
public class Employee {
private String name;
public Employee(String name) {
this.name = name;
}
public void display() {
System.out.println(this.name);
}
}Interview Tip: A concise interview answer is:
"The this keyword is a reference to the current object. It is mainly used to access instance variables, call current class methods or constructors, resolve variable naming conflicts, and refer to the current object within a class."