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

后端 未结 5 980
夕颜
夕颜 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:12

    1. Let's start with the constructor of Son.

      public Son() {
          super(); // implied
          who();
          tell(name);
      }
      
    2. Father's constructor is called.

      public Father() {
          who();
          tell(name);
      }
      
    3. Because who() is overridden by Son, the Son's version will be called, printing "this is son".

    4. tell() is also overridden but the value passed in is Father.name, printing "this is father".

    5. Finally, the who() and tell(name) calls inside Son's constructor will be made printing "this is son" and "this is son" respectively.

提交回复
热议问题