Java Reference
In-Depth Information
no longer need to worry about storing minutes of 60 or greater. All minutes added are
properly grouped into the common total.
The constructor and
toString
method also require minor modifications to
account for our new representation. Here is the complete class, implemented with
total minutes instead of hours and minutes. This version is shorter and simpler than
the original:
1 // Represents a time span of elapsed hours and minutes.
2 // Second implementation using a single field for total minutes.
3 // Class invariant: totalMinutes >= 0
4
5
public class
TimeSpan {
6
private int
totalMinutes;
7
8 // Constructs a time span with the given interval.
9 // pre: hours >= 0 && minutes >= 0
10
public
TimeSpan(
int
hours,
int
minutes) {
11 totalMinutes = 0;
12 add(hours, minutes);
13 }
14
15 // Adds the given interval to this time span.
16 // pre: hours >= 0 && minutes >= 0
17
public void
add(
int
hours,
int
minutes) {
18
if
(hours < 0 || minutes < 0) {
19
throw new
IllegalArgumentException();
20 }
21 totalMinutes += 60 * hours + minutes;
22 }
23
24 // returns a String for this time span, such as "6h 15m"
25
public
String toString() {
26
return
(totalMinutes / 60) + "h " +
27 (totalMinutes % 60) + "m";
28 }
29 }
As another example, we could revisit our encapsulated
Point
class and change its
internal structure without having to modify the client code. For example, sometimes
it is useful to express two-dimensional points in polar coordinates in terms of a radius
r
and an angle
theta
. In this representation, the (
x, y
) coordinates of a point are not
stored directly but can be computed as (
r
cos
theta, r
sin
theta
). When the
Point
class is encapsulated, we can modify it to use
r
and
theta
fields internally, then mod-
ify
getX
,
getY
, and other methods so that they still return appropriate values. The
Search WWH ::
Custom Search