这是代码,我定义了两个名为Father和Son的类,并在main函数中创建它们:
public class Test {
public static void main(String[] args) {
Father father = new Son();
}
}
class Father {
private String name = "father";
public Father() {
who();
tell(name);
}
public void who() {
System.out.println("this is father");
}
public void tell(String name) {
System.out.println("this is " + name);
}
}
class Son extends Father {
private String name = "son";
public Son() {
who();
tell(name);
}
public void who() {
System.out.println("this is son");
}
public void tell(String name) {
System.out.println("this is " + name);
}
}
Run Code Online (Sandbox Code Playgroud)
我得到了这样的输出:
this is son
this is father
this is son
this is son
Run Code Online (Sandbox Code Playgroud)
但我无法理解这是怎么发生的?谁能告诉我为什么?
让我们从构造函数开始Son.
public Son() {
super(); // implied
who();
tell(name);
}
Run Code Online (Sandbox Code Playgroud)父亲的构造函数被称为.
public Father() {
who();
tell(name);
}
Run Code Online (Sandbox Code Playgroud)因为who()被覆盖了Son,所以Son将调用版本,打印"这是儿子".
tell()也被覆盖,但传入的价值是Father.name,打印"这是父亲".
最后,who()和tell(name)里面调用Son类的构造函数将进行打印'这是儿子’,并分别'这是儿子’.
以下是所谓的:
new Son()
=>
Son._init
=> first every constructor calls super()
Father._init
Object._init
who() => is overridden, so prints "son"
tell(name) => name is private, so cannot be overridden => "father"
who() => "son"
tell(name) => "son"
Run Code Online (Sandbox Code Playgroud)
经验教训:
| 归档时间: |
|
| 查看次数: |
365 次 |
| 最近记录: |