Answer:
Clock Java:
public class Clock {
private int hours;
private int minutes;
private int seconds;
// Constructor to initialize hours, minutes, and seconds
public Clock(int hours, int minutes, int seconds) {
this.hours = hours;
this.minutes = minutes;
this.seconds = seconds;
}
// Constructor to initialize hours and minutes (seconds default to 0)
public Clock(int hours, int minutes) {
this(hours, minutes, 0);
}
// Constructor to initialize hours (minutes and seconds default to 0)
public Clock(int hours) {
this(hours, 0, 0);
}
// No-arg constructor (initializes all fields to 0)
public Clock() {
this(0, 0, 0);
}
// Method to reset the clock to 0
public void reset() {
this.hours = 0;
this.minutes = 0;
this.seconds = 0;
}
// Method to advance the clock by one second
public void tick() {
seconds++;
if (seconds == 60) {
seconds = 0;
minutes++;
if (minutes == 60) {
minutes = 0;
hours++;
if (hours == 24) {
hours = 0;
}
}
}
}
// Getters and setters for hours, minutes, and seconds
public int getHours() {
return hours;
}
public void setHours(int hours) {
this.hours = hours;
}
public int getMinutes() {
return minutes;
}
public void setMinutes(int minutes) {
this.minutes = minutes;
}
public int getSeconds() {
return seconds;
}
public void setSeconds(int seconds) {
this.seconds = seconds;
}
// toString method to display the time in "hh:mm:ss" format
public String toString() {
return String.format("%02d:%02d:%02d", hours, minutes, seconds);
}
}
Test.Clock Java
public class TestClock {
public static void main(String[] args) {
// Testing Clock class
Clock clock1 = new Clock(10, 30, 45);
Clock clock2 = new Clock(8, 15);
Clock clock3 = new Clock(4);
Clock clock4 = new Clock();
System.out.println("Clock 1: " + clock1.toString());
System.out.println("Clock 2: " + clock2.toString());
System.out.println("Clock 3: " + clock3.toString());
System.out.println("Clock 4: " + clock4.toString());
clock1.reset();
System.out.println("Clock 1 after reset: " + clock1.toString());
clock2.tick();
System.out.println("Clock 2 after ticking: " + clock2.toString());
// Testing getters and setters
clock3.setHours(12);
clock3.setMinutes(45);
clock3.setSeconds(20);
System.out.println("Clock 3 after setting values: " + clock3.toString());
}
}
Step-by-step explanation: