Here is my homework question:
Write a class declaration for a class “Clock”. It should have instance variables for hours, minutes, seconds (all integers). It should also have a toString() method to show the time in the format shown below. Write a separate “ClockDriver” class to a) create an instance of a clock, b) set the hours, minutes, and seconds for the clock, and c) show the time of the Clock using getTime(). Use the Dog class example on page 36 as a guide. Sample out is shown below:
The time is 3:45:00
// don’t worry if you can’t get both zeros in
// the second field. That is a formatting issue
// we will deal with later
Here is my Clock class:
class Clock {
int hours;
int minutes;
int seconds;
public String toString() {
String temp = ("");
return temp.format("%02d:%02d:%02d", hours, minutes, seconds);
} //end method toString
public void getTime() {
System.out.print("The time is " + toString());
} //end method getTime
} //end class Clock
And here is my ClockDriver class:
public class ClockDriver {
public static void main (String[] args) {
Clock c = new Clock();
c.hours = 4;
c.minutes = 30;
c.seconds = 00;
c.getTime();
} //end main
} //end class ClockDriver
Even though it compiles fine and works nicely, I get what I think is a warning from IDE saying that my
return temp.format("%02d:%02d:%02d", hours, minutes, seconds);
line is accessing a static member via instance reference. Specifically, the
temp.format
bit.
So my questions are:
1.) Why is accessing a static member via instance reference not necessarily encouraged?
2.) Is there a better way to put this together so that I'm not accessing a static member via instance reference?
Thanks in advance!