Shadowing and the this Keyword

A parameter can share its name with an instance variable. The Lighthouse class below has a method where that happens: extraReach is meant to report how much farther the light reaches than a given distance.
public class Lighthouse
{
private int range;
public Lighthouse(int r)
{
range = r;
}
public int extraReach(int range)
{
return range - range;
}
}
For Lighthouse point = new Lighthouse(18);, the call point.extraReach(12) returns 0, and so does every other call. Inside extraReach, both names in range - range mean the parameter, so the method subtracts a number from itself. The class compiles with no error.
The constructor has no such problem, because its parameter is named r, so range there can only be the instance variable.
The keyword this
Written with this, the method works.
public int extraReach(int range)
{
return this.range - range;
}
this.range names the current object's field, and range alone is the parameter. Now point.extraReach(12) returns 6. A setter whose parameter is named after the field needs the same fix: in setRange(int range), the statement must be this.range = range;, since range = range; just copies the parameter onto itself.
Passing the current object
Since this is a reference, it can be an argument. A Harbor class records lighthouses with a method log(Lighthouse lh), and a lighthouse can report itself.
public void reportTo(Harbor h)
{
h.log(this);
}
After Harbor bay = new Harbor();, the call point.reportTo(bay); runs log on the harbor bay, and its parameter lh receives a reference to the lighthouse point.