Implement a class Clock . Whose job it is to return the current time in UTC (Coo
ID: 3910632 • Letter: I
Question
Implement a class Clock. Whose job it is to return the current time in UTC (Coordinated Universal Time).
Clock should have three public methods:
getHours - which returns the current hour as an int.
getMinutes - which returns the current minute as an int.
getTime - which returns, as a string the full time (concatenating the results of getHours and getMinutes).
The getHours and getMinutes methods should work by invoking java.time.Instant.now().toString() and then extract the relevant portion of that string to figure out what to return.
Next, provide another class WorldClock that is a subclass of Clock. The constructor for WorldClass will accept a time offset. For example, new WorldClock(-4) should show the time in currently in New York since we are currently on EDT which 4 hours behind UTC. To do this you will need to override one of the three methods listed above. You must not override getTime.
You’ve been provided with a ClockTester.java that shows some example use cases of the two classes. As well as an empty Clock.java and WorldClock.java.
Explanation / Answer
Hi,
Please find the classes below. It would be great if you provide the tester java class to know the class design better.However, based on the specification below are the classes.
------------
public class Clock {
private String timeString;
private int hours;
private int minutes;
//Constructor
public Clock() {
this.timeString=java.time.Instant.now().toString();
}
// returns the current hour as an int.
public int getHours() {
String[] time = timeString.split("T");
String[] temp = time[1].split(":");
hours = Integer.parseInt(temp[0].trim());
return hours;
}
//which returns the current minute as an int.
public int getMinutes() {
String[] time = timeString.split("T");
String[] temp = time[1].split(":");
minutes = Integer.parseInt(temp[1].trim());
return minutes;
}
//which returns, as a string the full time.
public String getTime() {
return getHours()+":"+getMinutes();
}
}
----------------
public class WorldClock extends Clock {
private int offset;
//Constructor
public WorldClock(int offset) {
this.offset=offset;
}
@Override
public int getHours() {
return super.getHours() + offset;
}
}
----------------------
package clock;
public class ClockTester {
public static void main(String[] args) {
Clock c=new Clock();
System.out.println("Clock Time:=" + c.getTime());
System.out.println("Clock Hours:=" + c.getHours());
System.out.println("Clock Mins:=" + c.getMinutes());
WorldClock wc= new WorldClock(-4);
System.out.println("WorldClock Time:="+ wc.getHours());
System.out.println("WorldClock Hours:=" + wc.getHours());
System.out.println("WorldClock Mins:=" + wc.getMinutes());
}
}
-----------------------------------------------
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.