public class Time implements Comparable {
// constrants (final) class variables
static public final int HOURS_PER_DAY = 24;
static public final int MINUTES_PER_HOUR = 60;
static public final int SECONDS_PER_MINUTE = 60;
// instance variables
private int hours;
private int minutes;
private int seconds;
// constructor
public Time (int hours, int minutes, int seconds) {
this.hours = hours;
this.minutes = minutes;
this.seconds = seconds;
normalize ();
}
// access instance methods
public int getHours () {
return hours;
}
public int getMinutes () {
return minutes;
}
public int getSeconds () {
return seconds;
}
// standard instance methods
public String toString() {
return getHours ()+”:”+getMinutes ()+”:”+getSeconds ();
}
public boolean equals(Time t) {
return ( (hours == t.getHours())
&& (minutes == t.getMinutes())
&& (seconds == t.getSeconds()));
}
public boolean before(Time t) {
return ((getHours () < t.getHours ()) ||
((getHours () == t.getHours ()) && (getMinutes () < t.getMinutes () )) ||
((getHours () == t.getHours ()) && (getMinutes () == t.getMinutes ()) &&
(getSeconds () < t.getSeconds ())));
}
public boolean after(Time t) {
return ((getHours () > t.getHours ()) ||
((getHours () == t.getHours ()) &&
(getMinutes () > t.getMinutes () )) ||
((getHours () == t.getHours ()) &&
(getMinutes () == t.getMinutes ()) &&
(getSeconds () > t.getSeconds ())));
}
public int compareTo(Comparable obj) {
Time other;
other = (Time) obj;
int result;
if (before(other)) {
result = -1;
} else if (after(other)) {
result = 1;
} else { // equals
result = 0;
}
return result;
}
// other instance methods
public void increase() {
seconds++ ;
normalize ();
}
// private instance method
private void normalize () {
int carry = seconds / SECONDS_PER_MINUTE;
seconds = seconds % SECONDS_PER_MINUTE;
minutes = minutes + carry ;
carry = minutes / MINUTES_PER_HOUR;
minutes = minutes % MINUTES_PER_HOUR;
hours = (hours + carry) % HOURS_PER_DAY;
}
}