These notes recap Topic 3.9. For worked examples, read the study guide.
Recap
- In an instance method or constructor,
thisis a special variable holding a reference to the current object: the object whose method or constructor is being run. this.name = name;stores the parameternamein the instance variablename, solving the hiding problem of Topic 3.8.thiscan be passed as an argument so that one object can give another a reference to itself, as int.setCaptain(this).this == othertests whether two references refer to the same object.this.age > other.agecompares the values held by the two objects.- Class methods do not have a
thisreference.
Key relationships
| Expression | Meaning |
|---|---|
this |
The object before the dot in the call, or the object being constructed |
this.age |
The age instance variable of the current object |
age (with a parameter called age) |
The parameter |
age (with no hiding) |
The instance variable, the same as this.age |
t.setCaptain(this) |
Passes a reference to the current object |
this == other |
true only if both are the same object |
Worked reminder
With Pet a = new Pet("Rex", 4), Pet b = new Pet("Tia", 7) and Pet c = a: a.sameObjectAs(c) is true, a.sameObjectAs(b) is false, a.olderThan(b) is false (4 > 7) and b.olderThan(a) is true (7 > 4), because this is a in the first calls and b in the last. After p.becomeCaptainOf(team), the team’s captain is the same object as p: team.getCaptain() == p is true.
Using this in class-design questions
- In a constructor that takes parameters named like the instance variables, begin each assignment with
this.on the left. - When another method needs to know which object is calling it, pass
this. - When a method compares two objects of the same class, write the current object as
thisand the other as the parameter. - Never use
thisinside a method declaredstatic; pass an object in as a parameter instead.
Assumptions
thisexists only in instance methods and constructors.- A reference-typed instance variable that is never set holds
null. - Without a hiding parameter,
this.is optional.
Compile errors to recognise
| Message | Cause |
|---|---|
non-static variable this cannot be referenced from a static context |
this used in a class method |
Mistakes to avoid
- Writing
name = name;in a constructor instead ofthis.name = name;. - Writing
name = this.name;(reversed), which leaves the instance variable unchanged. - Using
thisin astaticmethod. - Thinking
thisis a fixed object rather than the object before the dot. - Using
==to compare contents.
Quick self-check
- What does
this.score = score;do whenscoreis also a parameter? Answer: stores the parameter in the instance variable. - In
x.show(), what doesthisrefer to insideshow? Answer: the objectxrefers to. - Can
thisbe used in astaticmethod? Answer: No. - A method contains
other.setBuddy(this);. What doesotherreceive? Answer: a reference to the object running the method.