boolean equals( Rectangle r ) ;Suppose we're writing the method definition. Normally, if you have a parameter variable, you can only access its public methods. Parameter variables do not have any special privileges.
But what happens if the type of the parameter variable is the same as the type of the class? In this case, the parameter variable has type Rectangle, which is the same as the class.
Java allows you to access the instance variables of parameter variables of the same type as the class directly.
public class Rectangle { public boolean equals( Rectangle r ) { return width == r.width && height == r.height ; } }The remaining methods have been left out for brevity.
Notice that we access r.width and r.height. These are the instance variables of parameter variable r.
Had the parameter been a different type, it wouldn't have worked. The Java compiler would have said there was an error trying to access private instance variables of a different type.
Now just because we accessed the private instance variables
of the parameter didn't mean we were forced to
do so. We could have written the method by using public
methods.
public class Rectangle
{
public boolean equals( Rectangle r )
{
return getWidth() == r.getWidth() && getHeight() == r.getHeight() ;
}
}
The method call getWidth() is the same as this.getWidth().