The return statement causes a method to stop executing its body and return execution to the invoking
method. If an expression is part of the return statement then the value of that expression is returned as the
value of the method invocation. The type of the expression must be compatible with the return type defined
for the method. In the example we use the sqrt method of the Math library class to calculate the square root
of the sum of the squares of the differences between the two x and y coordinates.
Based on the lowerLeft and upperRight objects created previously, you could invoke distance this
way:
double d = lowerLeft.distance(upperRight);
Here upperRight is passed as an argument to distance, which sees it as the parameter that. After this
statement executes, the variable d contains the Euclidean distance between lowerLeft and upperRight.
1.8.2. The this Reference
Occasionally, the receiving object needs to know its own reference. For example, the receiving object might
want to add itself to a list of objects somewhere. An implicit reference named this is available to methods,
and this is a reference to the current (receiving) object. The following definition of clear is equivalent to
the one just presented:
public void clear() {
this.x = 0.0;
this.y = 0.0;
}
You usually use this as an argument to other methods that need an object reference. The this reference
can also be used to explicitly name the members of the current object. Here's another method of Point
named move, which sets the x and y fields to specified values:
public void move(double x, double y) {
this.x = x;
this.y = y;
}
The move method uses this to clarify which x and y are being referred to. Naming the parameters x and y
is reasonable, because you pass x and y coordinates to the method. But then those parameters have the same
names as the fields, and therefore the parameter names hide the field names. If we simply wrote x=x we
would assign the value of the x parameter to itself, not to the x field as required. The expression this.x
refers to the object's x field, not the x parameter of move.
Exercise 1.8: Add a method to the Point class that sets the current object's coordinates to those of a passed
in Point object.