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?
If you are using an ide like eclipse, you might have noticed a mark near your method toString() that says overrides java.lang.Object.toString
. This is the method that is being called by default when you are trying to print an object. This looks like
* @return a string representation of the object.
*/
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
Since you have your own definitions inside the method by the same name, it is getting overridden. You can notice the difference if you rename your own toString
method to something else, and the output would be something like Time1@2a139a55
The problem is in your toString
method. What the following does
((hour==0 || hour==12)?12:hour%12)
is, whenever the value of hour is either 0
or 12
, print 12, otherwise print hour % 12
.
When you call:
System.out.println(thistime);
the print result will be the same as:
System.out.println(thistime.toString());
so this is why the toString
method is invoked. You can write something like ((hour == 12) ? 12 : hour % 12)
to fix it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With