//Default constructor
public
Time() {
setTime(0, 0, 0);
}
//Alternate constructor with parameters, to set the time
public
Time(int h, int m, int s) {
setTime(h, m, s);
}
//Copy constructor
public
Time(Time otherTime) {
setTime(otherTime.hrs, otherTime.mins, otherTime.secs);
}
//clone; without this, compile error in client (.clone protected)
public
Object clone() {
try {
return super.clone();
}
catch (CloneNotSupportedException e) {
return null;
}
}
public
void setTime(int h, int m, int s) {
hrs = (h >= 0 && h < 24)? h : 0;
mins = (m >= 0 && m < 60)? m : 0;
secs = (s >= 0 && s < 60)? s : 0;
}
public
int getHours() {
return hrs;
}
public
int getMinutes(){
return mins;
}
public
int getSeconds() {
return secs;
}
//Time is printed in the form HH:MM:SS
public
void printTimeMilitary(){
System.out.print((hrs < 10? "0": "") + hrs + ":");
System.out.print((mins < 10? "0": "") + mins + ":");
System.out.print((secs < 10? "0": "") + secs);
}
//Time is printed in the form HH:MM:SS AM/PM
public
void printTimeStandard(){
System.out.print((hrs == 0 || hrs == 12? 12: hrs % 12) + ":");
System.out.print((mins < 10? "0": "") + mins + ":");
System.out.print((secs < 10? "0": "") + secs + " ");
System.out.print((hrs < 12? "AM": "PM"));
}
public
String toString() {
String str = "";
if (hrs < 10)
str = "0";
str = str + hrs + ":";
if (mins < 10)
str = str + "0" ;
str = str + mins + ":";
if (secs < 10)
str = str + "0";
str = str + secs;
return str;
}
public
void incrementHrs() {
hrs++;
if(hrs > 23)
hrs = 0;
}
public
void incrementMins() {
mins++;
if(mins > 59){
mins = 0; //call incrementHrs() OR:
hrs++;
if(hrs > 23)
hrs = 0;
}
}
public
void incrementSecs(){
secs++;
if(secs > 59){
secs = 0; //call incrementMins() OR:
mins++;
if(mins > 59){
mins = 0;
hrs++;
if(hrs > 23)
hrs = 0;
}
}
}
public
boolean equals(Object otherTime) {
Time temp = (Time) otherTime;
return (hrs == temp.hrs && mins == temp.mins && secs ==
temp.secs);
}
public
int compareTo(Object othertime) {
Time temp = (Time) othertime;
int hrDiff = hrs - temp.hrs;
if (hrDiff != 0)
return hrDiff;
int minDiff = mins - temp.mins;
if (minDiff != 0)
return minDiff;
return secs - temp.secs;
}
}
//Class:
ClientTimeClone
public class ClientTimeClone
{
public
static void main(String[] args) {
Time t1 = new Time(1, 2, 3);
System.out.println("t1: " + t1);
Time t2 = (Time) t1.clone();
System.out.println("Copy t1 using .clone(). After copy, t2: " + t2);
if (t1 == t2)
System.out.println("Both t1 and t2 refer to the same object.");
else
System.out.println("t1 and t2 DON'T refer to the same object.");
t1.setTime(11, 12, 13);
System.out.println("Changed t1 to 11:12:13. After change:");
System.out.println("t1: " + t1);
System.out.println("t2: " + t2);
}
}
OUTPUT:
t1: 01:02:03
Copy t1 using .clone().
After copy, t2: 01:02:03
t1 and t2 DON'T refer
to the same object.
Changed t1 to 11:12:13.
After change:
t1: 11:12:13
t2: 01:02:03