Java Reference
In-Depth Information
8 Point p2 = new Point(4, 3);
9
10 // print each point and its distance from the origin
11 System.out.println("p1 is " + p1);
12 System.out.println("distance from origin = " +
13 p1.distanceFromOrigin());
14 System.out.println("p2 is " + p2);
15 System.out.println("distance from origin = " +
16 p2.distanceFromOrigin());
17
18 // translate each point to a new location
19 p1.translate(11, 6);
20 p2.translate(1, 7);
21
22 // print the points again
23 System.out.println("p1 is " + p1);
24 System.out.println("p2 is " + p2);
25 }
26 }
Class Invariants
In this section we will develop another new class to illustrate a particular benefit of
encapsulation. Consider a program that measures or deals with elapsed intervals of
time, such as a program for a stopwatch, a scheduler, a TV recorder, or an airline
flight system. A useful abstraction in such a program would be an object representing
an elapsed span of time.
Let's write a class called TimeSpan , in which each TimeSpan object represents an
interval of elapsed hours and minutes. For example, we could construct a TimeSpan
representing an interval of 6 hours and 15 minutes. We'll represent only hours and
minutes, ignoring larger or smaller units such as days or seconds.
Since we're representing intervals of hours and minutes, it seems natural to use
these two quantities as fields in our class. We will encapsulate the class properly from
the start by declaring the fields as private :
// represents a time span of elapsed hours and minutes
public class TimeSpan {
private int hours;
private int minutes;
...
}
The constructor for a TimeSpan object will accept hours and minutes as parame-
ters and store the values into the object's fields. However, there is a potential prob-
lem: What should we do about values of minutes that are 60 or greater? Should the
 
Search WWH ::




Custom Search