Java Reference
In-Depth Information
used the translate method, we'll refer to the Point object's x and y fields directly
in our computation:
// returns the distance between this point and (0, 0)
public double distanceFromOrigin() {
return Math.sqrt(x * x + y * y);
}
Note that the distanceFromOrigin method doesn't change the Point object's x
or y values. Accessors are not used to change the state of the object—they only report
information about the object. You can think of accessors as read-only operations
while mutators are read-write operations.
A typical accessor will have no parameters and will not have a void return type,
because it must return a piece of information. An accessor returns a value that is part
of the state of the object or is derived from it. The names of many accessors begin
with “get” or “is,” as in getBalance or isEmpty .
Here's the complete second version of our Point class that now contains both
state and behavior:
1 // A Point object represents a pair of (x, y) coordinates.
2 // Second version: state and behavior.
3
4 public class Point {
5 int x;
6 int y;
7
8 // returns the distance between this point and (0, 0)
9 public double distanceFromOrigin() {
10 return Math.sqrt(x * x + y * y);
11 }
12
13 // shifts this point's location by the given amount
14 public void translate( int dx, int dy) {
15 x += dx;
16 y += dy;
17 }
18 }
The client program can now use the new behavior of the Point class. The pro-
gram produces the same output as before, but it is shorter and more readable than the
original. The following lines show examples of the changes made to PointMain :
System.out.println("distance from origin = " + p1.distanceFromOrigin());
...
p1.translate(11, 6);
 
Search WWH ::




Custom Search