Expanded TimeOfDay class

  1 
  2 
  3 
  4 
  5 
  6 
  7 
  8 
  9 
 10 
 11 
 12 
 13 
 14 
 15 
 16 
 17 
 18 
 19 
 20 
 21 
 22 
 23 
 24 
 25 
 26 
 27 
 28 
 29 
 30 
 31 
 32 
 33 
 34 
 35 
 36 
 37 
 38 
 39 
 40 
 41 
 42 
 43 
 44 
 45 
 46 
 47 
 48 
 49 
 50 
 51 
 52 
 53 
 54 
 55 
 56 
 57 
 58 
 59 
 60 
// File   : oop/timeofday/TimeOfDay4.java
// Purpose: A 24 hour time-of-day class to demo intro OOP concepts.
// Author : Fred Swartz - 2006-09-18 - Placed in public domain.

public class TimeOfDay4 implements Comparable<TimeOfDay4>, Cloneable {
    //============================================= instance variables
    private int _totalMinutes;     // Minutes after midnight.

    //===================================================== constructor
    public TimeOfDay4(int h, int m) {
        //... Check values for validity.
        if (h < 0 || h > 23 || m < 0 || m > 59) {
            throw new IllegalArgumentException(
                "TimeOfDay4: Illegal value: " + h + ":" + m);
        }
        _totalMinutes = h * 60 + m;
    }

    //========================================================= getHour
    public int getHour() {
        return _totalMinutes / 60;
    }

    //======================================================= getMinute
    public int getMinute() {
        return _totalMinutes % 60;
    }

    //======================================================== toString
    @Override public String toString() {
        return getHour() + ":" + getMinute();
    }
    
    //======================================================= compareTo
    public int compareTo(TimeOfDay4 other) {
    	return _totalMinutes - other._totalMinutes;
    }

    //========================================================== equals
    @Override public boolean equals(Object other) {
        if (this == other) return true;
        if (other == null) return false;
        if (this.getClass() != other.getClass()) return false;
        return _totalMinutes == ((TimeOfDay4)other)._totalMinutes;
    }

    //=========================================================== clone
    @Override public TimeOfDay4 clone() {
        TimeOfDay4 result;
        try {
            result = (TimeOfDay4) super.clone();
            //... We're done because Object.clone copies all fields.
            //    Would have to do more only if any of our fields
            //    were references to mutable objects.
        } catch (java.lang.CloneNotSupportedException unused) {
            result = null;   // But can't fail!
        }
        return result;
    }
}