This is an example I was working on from my java tutorial. I have a Time1 class that does not have a constructor, and hence I was expecting it to be initialized with the default values to int, that is zero.
public class Time1 {
private int hour; // expected to be initialised with zero
private int minute; // expected to be initialised with zero
private int second; // expected to be initialised with zero
public void setTime(int hour, int minute, int second) {
if (hour < 0 || hour >= 24 || minute < 0 || minute >= 60 || second < 0 || second >= 60) {
throw new IllegalArgumentException("value out of range");
}
this.hour = hour;
this.minute = minute;
this.second = second;
}
public String toUniversalString() {
return String.format("%02d:%02d:%02d", hour, minute, second);
}
public String toString() {
return String.format("%d:%02d:%02d %s", ((hour == 0 || hour == 12) ? 12 : hour % 12), minute, second, (hour < 12 ? "AM" : "PM"));
}
}
And now I have the main class
public class Time1test {
public static void main(String[] args) {
Time1 thistime = new Time1();
System.out.println(thistime);
thistime.setTime(13, 22, 33);
System.out.println(thistime);
}
}
I was expecting System.out.println(thistime); before using the setTime() method to return 00:00:00 because I haven't used any methods to reformat it, however I am getting the output as 12:00:00 AM, that is equal to calling toString() method. Why was this method being called by default when a new object is initialized, even without being called for?
00:00:00? Did you expect Java to automatically calltoUniversalString?Objectto print, like this:System.out.println(Object), it really just doesSystem.out.println(Object.toString())