Card 06/ 09

ConceptDifficulty: Intermediate1 min

What this Refers To, and the One Place It Is Not Optional

A constructor that assigns its parameters to its fields, written without this, compiles cleanly and leaves every field null.

java
Order(String customer, double total) {
    customer = customer;
    total = total;
}

Inside any instance method or constructor, this is the object the code is currently running on. It is always available and almost always optional: writing status and this.status mean the same thing, because the compiler looks at fields when nothing nearer matches.

The exception is when something nearer does match. A parameter called customer shadows the field called customer, so both sides of line 2 are the parameter, and the assignment does nothing at all.

What each spelling names when a parameter shares a field's name
WrittenNames
customerThe parameter, because it is nearer
this.customerThe field on this object, always

So this. is required exactly where a name is shadowed, which in practice is every constructor that names its parameters after its fields — and naming them that way is the right choice, because the parameter list then documents itself.