TOPIC 3.9 · STUDY
this Keyword
Inside an instance method or constructor, this is the current object. this.ink = ink stores the parameter in the field when the names match. A call such as desk.stamp() makes this refer to desk, so another object is unchanged.
3.9.A
The this keyword
Inside a constructor or an instance method, this means the current object: the one being constructed, or the one the method was called on. It is not every object of the class. When a parameter uses the same name as a field, the bare name means the parameter. Write this.field to name the instance variable. Without this, an assignment such as ink = ink only updates the parameter and leaves the field at its default.
class Marker {
private int ink;
public Marker(int ink) {
this.ink = ink;
}
public int left() {
return this.ink;
}
}
Marker desk = new Marker(10);
System.out.print(desk.left());
In the constructor, this is the new Marker. this.ink = ink stores the parameter 10 in that object's field, so left prints 10. Writing ink = ink instead would leave the field at 0.
class Marker {
private int ink;
public Marker(int ink) {
this.ink = ink;
}
public void stamp() {
this.ink -= 2;
}
public int left() {
return this.ink;
}
}
Marker desk = new Marker(10);
Marker hall = new Marker(10);
desk.stamp();
System.out.print(desk.left() + "," + hall.left());
desk.stamp() runs with this bound to desk, so only desk drops by 2. hall is a different Marker, so the print is 8,10. The same stamp method exists for both objects, but this always names the receiver of that call.
During desk.stamp(), this points at desk only. hall is untouched.
You can also pass this as an argument so another method receives the current object. Class methods (static methods) have no current object, so this is illegal there even if objects of the class already exist.
Key points
- In a constructor or instance method, this is the current object.
- this.ink = ink stores the parameter in the field when the names match.
- A bare name that matches a parameter means the parameter, not the field.
- desk.stamp() binds this to desk; a different object is unchanged.
- You may pass this to another method as the current object.
- A class (static) method cannot use this.
this is the object the method was called on, not every object of the class.