我将这组精简的类文件作为 OO 的示例。它们工作得很好,但我不明白来自WorkerTest.javaprintln
的调用是如何通过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