7.9 Putting Things Together
In this section, we simply write an example program that demonstrates many of the concepts we have discussed in this chapter. This example is a modified version of an example written by Sun, called Clock. A Clock object is created, which has hour, minute, and second values. A method displays the current time once the Clock is created using either its default no-arg constructor or another constructor that defines a custom time setting. When the Clock object's tick() method is called, the second value increments by one, possibly changing the hour and minute values on the clock. We need two listings for this exampleone that creates the Clocks, holds their values, and defines their methods, and another that instantiates the Clocks:
7.9.1 MakeClocks.java
package chp7; // based on Sun's Clock class // here I've only consolidated using the getTime method class MakeClock { public static void main (String args[]) { // no-arg constructor Clock c1 = new Clock(); // set initial time on clock two Clock c2 = new Clock(59, 59, 1); System.out.println("Initial time:"); System.out.println(c1.getTime()); System.out.println(c2.getTime()); System.out.println("Time after increment: " ); c1.tick(); System.out.println(c1.getTime()); c2.tick(); System.out.println(c2.getTime()); } // end main }
7.9.2 Clock.java
package chp7; public class Clock { // declare private vars, which means that only methods of the /// current class can use them private int second, minute, hour; // clock method sets values // use 'this' to refer to the declared class-level vars above public Clock(int s, int m, int h) { this.second = s; this.minute = m; this.hour = h; } // constructor method sets defaults public Clock() { this.second = 0; this.minute = 0; this.hour = 0; } public void setSecond(int s) { if (s >= 0 && s < 60) { this.second = s; } else { System.out.println("Invalid seconds value, not set."); } } public void setMinute(int m) { if (m >= 0 && m < 60) { this.minute = m; } else { System.out.println("Invalid minutes value, not set."); } } public void setHour (int h) { if (h >= 0 && h < 24) { this.hour = h; } else { System.out.println("Invalid hours value."); } } public void setTime(int s, int m, int h) { setSecond(s); setMinute(m); setHour(h); } public void tick() { second++; if (second==60) { second = 0; minute++; if (minute==60) { minute=0; hour++; if (hour==24) { hour = 0; } } } } public int getSecond() { return second; } public int getMinute() { return minute; } public int getHour() { return hour; } public String getTime(){ String s = Integer.toString(getHour()) + ":" + Integer.toString(getMinute()) + ":" + Integer.toString(getSecond()); return s; } } // end class
The output is as follows:
Initial time: 0:0:0 1:59:59 Time after increment: 0:0:1 2:0:0