The this Keyword
"This object"
- Inside an instance method,
thisrefers to the object the method was called on. student.addScore(10)runs withthis= thatstudent.this.scoremeans "thescoreof the object I'm working on."- It lets a method talk about its own object explicitly.
Distinguishing field from parameter
- The main use: tell an instance variable apart from a parameter of the same name.
void setName(String name) { this.name = name; }this.nameis the instance variable; plainnameis the parameter.- This is the standard fix for the shadowing bug from 3.8.
Access to the calling object
thisgives a method a handle on the exact object it was called on.- Every instance method has an implicit
this, whether you write it or not. score += s;is reallythis.score += s;—thisis usually left implicit.- You write
thisexplicitly only when needed (like resolving shadowing).
No this in a static method
- A static method has no
this— it isn't tied to any particular object. - So a static method can't use
thisor read instance variables directly. - Trying to use
thisin a static method is a compile error. - If you need
this, the method must be an instance method, not static.
Use this.field = param; to defeat shadowing — this.name is the instance variable, plain name is the parameter. Writing name = name; (no this) just assigns the parameter to itself. And this doesn't exist in a static method — a static method has no particular object, so using this there won't compile.
Fixing the shadowing bug with this:
- Instance variable
private String name; void setName(String name) { this.name = name; }— correct!this.name(the field) gets the value ofname(the parameter).
this refers to the current object — the one an instance method was called on. Its key use is resolving shadowing: this.name = name; assigns the parameter to the instance variable. Every instance method has an implicit this, but a static method has none, so this can't be used there.
this refers to the calling object
Inside setName, this is the ada object it was called on.
Inside an instance method, this refers to...
this is a handle on the current object.
In setName(String name) { this.name = name; }, this.name is...
this.name is the field; plain name is the parameter.
The this keyword can be used inside a static method.
Static methods have no particular object, so no this.
Writing name = name; (no this) inside setName(String name) does what?
Both names are the parameter; use this.name to reach the field.
Every instance method has an implicit this, whether you write it or not.
score += s is really this.score += s.