import java.text.DecimalFormat; /* TimeOfDay.java ** An instance of this class represents an immutable time of day, ** precise to a minute. */ public class TimeOfDay { // class constants // --------------- private static final int HOUR_CEILING = 24; private static final int MINUTE_CEILING = 60; // instance variables // ------------------ private final int hour; // in range [0 .. HOUR_CEILING) private final int minute; // in range [0 .. MINUTE_CEILING) // constructor // ----------- /* Sets this TimeOfDay to the specified hour and minute. ** Throws an IllegalArgumentException if either parameter is ** outside its meaningful range. */ public TimeOfDay(int hr, int min) { if (hr < 0 || hr >= HOUR_CEILING) { throw new IllegalArgumentException("Hour parameter outside legal range."); } else if (min < 0 || min > MINUTE_CEILING) { throw new IllegalArgumentException("Minute parameter outside legal range."); } else { hour = hr; minute = min; } } // observers // --------- /* Two obvious "getter" methods. */ public int getHour() { return hour; } public int getMinute() { return minute; } /* Returns a string describing the time of day represented by this object. ** The form of the string is hh:mm, meaning a two-digit hour, a colon, and ** a two-digit minute. Examples: "08:02", "23:15". */ @Override public String toString() { DecimalFormat df = new DecimalFormat("00"); return df.format(hour) + ":" + df.format(minute); } }