我已經減少了一組類文件作爲OO的例子。他們完美地工作,但我不明白,從WorkerTest.java的println
呼叫如何使它一路過關斬將Worker.java和Date.java?這兩個Worker.java和Date.java有toString
方法,但都沒有明確調用,但我可以從輸出告訴我們都使用。這些方法如何被使用而不被調用?
這是如何工作,或我應該研究什麼概念?
public class WorkerTest {
public static void main(String[] args) {
Date birth = new Date(7, 15, 1922);
Worker worker = new Worker(birth);
System.out.println(worker);
}
}
public class Worker {
private Date birthday;
public Worker( Date inboundBirthday) {
birthday = inboundBirthday;
}
public String toString() {
return String.format("Birthday: %s", birthday);
}
}
public class Date {
private int month;
private int day;
private int year;
public Date(int inboundMonth, int inboundDay, int inboundYear) {
month = inboundMonth;
day = inboundDay;
year = inboundYear;
}
public String toString() {
return String.format("%d/%d/%d", month, day, year);
}
}
輸出: Birthday: 7/15/1922
我確定其他人可以更好地描述它,但是,如果您正在編寫的值不是'String',Java將自動在'Object'上調用'toString'。 – MadProgrammer 2013-02-18 04:21:34
相關問題:http://stackoverflow.com/questions/8555771/why-is-the-tostring-method-being-called-when-i-print-an-object – ajp15243 2013-02-18 04:21:57