Card 06/ 09

ConceptDifficulty: Intermediate1 min

The this Keyword, and When It Is Required

A constructor without this compiles cleanly and leaves the customer null.

Inside a constructor or an instance method, this means the object the code is running on. It is usually optional, and it becomes required when a parameter or local variable has the same name as a field, because the nearer name hides the field.

A constructor that assigns its parameters to its fields, written without this, compiles cleanly and leaves customer null and the total at zero:

java
Order(String customer, long totalPence) {
    customer = customer;
    totalPence = totalPence;
}

this 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, or hides, 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. In practice that 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.