What is the order of the Constructors in this Java Code?

后端 未结 5 973
夕颜
夕颜 2021-01-12 18:36

Here is the code, I defined two class named Father and Son, and create them in the main function:

public class Test {
    public static void main(String[] ar         


        
5条回答
  •  囚心锁ツ
    2021-01-12 19:18

    When you create the Son instance, the parent class' constructor is called (i.e. Father()); here the who() method is called, but it's the overridden version you declared in Son, so here's your first line (where the String is hardcoded inside the method).

    The second line comes from the tell(name) inside Father(), where tell() is overridden but name == "father" as the call comes from within Father's constructor, and name is a private field of class Father.

    Control goes back to Son() constructor, and the last two lines come straightforwardly from the Son class constructor.

提交回复
热议问题