Java constructor inheritance?

前端 未结 7 2000
一生所求
一生所求 2020-12-15 10:26

I always thought that constructors aren\'t inherited, but look at this code:

class Parent {
    Parent() {
        S         


        
7条回答
  •  伪装坚强ぢ
    2020-12-15 11:05

    Whatever you are seeing here is called as constructor chaining. Now What is Constructor Chaining:

    Constructor chaining occurs through the use of inheritance. A subclass constructor method's first task is to call its superclass' constructor method. This ensures that the creation of the subclass object starts with the initialization of the classes above it in the inheritance chain.

    There could be any number of classes in an inheritance chain. Every constructor method will call up the chain until the class at the top has been reached and initialized. Then each subsequent class below is initialized as the chain winds back down to the original subclass. This process is called constructor chaining.(Source)

    That's what happening in your program. When you compile your program , your Child is compiled to this way by javac:

    class Child extends Parent 
    { 
      Child()
      {
        super();//automatically inserted here in .class file of Child
        System.out.println("S2");
      }
    }
    

    And your Parent class is converted to following:

    Parent() 
    {
        super();//Constructor of Object class
        System.out.println("S1");
    }
    

    That's why your output is showing as:

    S1 //output from constructor of super class Parent
    S2 //output from constructor of child Class Child
    

提交回复
热议问题