this Keyword in Java — Java Technical Interview Questions & Answers
this Keyword in Java
this Keyword in Java
- this means this current object. In a constructor, this.name = name; copies the parameter into the field. Without this, name = name; only changes the local parameter — a very common bug.
- this.method() calls another method on the same object. this() calls another constructor in the same class and must be the first statement. static methods have no this, because there is no current object.
- Show the classic constructor this.name = name; in interviews.
- Let's take this on the board with one tiny Main class — no extra files. this Keyword in Java — output: Asha. Without this.name = name, the field would stay null — parameter would hide the field. Start from main, go line by line, and stop at each print. That output is the proof for this Keyword.
Technical Interview Tip: Show this.name = name in a constructor.
Code Examples for this Keyword in Java
Example
class Person {
String name;
Person(String name) {
this.name = name; // field = parameter
}
}
public class Main {
public static void main(String[] args) {
Person p = new Person("Asha");
System.out.println(p.name);
}
}this Keyword in Java — output: Asha. Without this.name = name, the field would stay null — parameter would hide the field.
How to Explain this Keyword in Java to an Interviewer
What does this mean?
The current object
Why this.name = name?
Parameter and field have the same name Sets the field
Can you use this in static?
No