Topic 3.9 — this Keyword
Goal: use this to refer to the current object, especially to resolve shadowing
and to access instance variables/methods from inside the class.
The big idea
Inside an instance method or constructor, this is a reference to the
current object (the object the method is running on).
You use this most often to fix shadowing and make it clear which variable is the field.
Where you can use this
- Inside instance methods (not static methods)
- Inside constructors
- To refer to instance variables and instance methods
Shadowing problem (common AP trap)
If a parameter has the same name as an instance variable, the parameter “hides” the instance variable.
public class Student {
private int grade;
public void setGrade(int grade) {
grade = grade; // ❌ sets the parameter to itself
}
}
The left grade is the parameter, not the field.
Fix using this
Use this.grade to mean “the field named grade.”
public void setGrade(int grade) {
this.grade = grade; // ✅ field = parameter
}
this in constructors
Same idea: it helps you initialize fields clearly.
public class Student {
private String name;
public Student(String name) {
this.name = name;
}
}
Calling instance methods with this
You can call methods like this.doThing(), but most of the time it’s optional.
public void reset() {
this.setGrade(0); // works
// setGrade(0); // also works (same object)
}
this is NOT used in static methods
Static methods don’t run on a specific object, so there is no “current object.”
public static void demo() {
// System.out.println(this); // ❌ not allowed
}
Quick self-check
- What does
thisrefer to? - Why does
grade = grade;usually do nothing useful? - Rewrite
name = name;correctly inside a constructor. - Can you use
thisin a static method? Why/why not? - Is
this.method()different frommethod()inside an instance method?