本Java代码中构造函数的顺序是什么?

ZRJ*_*ZRJ 6 java

这是代码,我定义了两个名为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)

但我无法理解这是怎么发生的?谁能告诉我为什么?

ada*_*shr 9

  1. 让我们从构造函数开始Son.

    public Son() {
        super(); // implied
        who();
        tell(name);
    }
    
    Run Code Online (Sandbox Code Playgroud)
  2. 父亲的构造函数被称为.

    public Father() {
        who();
        tell(name);
    }
    
    Run Code Online (Sandbox Code Playgroud)
  3. 因为who()被覆盖了Son,所以Son将调用版本,打印"这是儿子".

  4. tell()也被覆盖,但传入的价值是Father.name,打印"这是父亲".

  5. 最后,who()tell(name)里面调用Son类的构造函数将进行打印'这是儿子’,并分别'这是儿子’.


Thi*_*ilo 6

以下是所谓的:

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)

经验教训:

  • 私有字段和方法是私有的.不能被覆盖.
  • 不要从可以被覆盖的构造函数中调用方法.这可以调用半初始化类状态的方法(尽管不会发生在你的情况下).