super() in Java

前端 未结 15 2241
逝去的感伤
逝去的感伤 2020-11-22 05:36

Is super() used to call the parent constructor? Please explain super().

15条回答
  •  北荒
    北荒 (楼主)
    2020-11-22 05:50

    As stated, inside the default constructor there is an implicit super() called on the first line of the constructor.

    This super() automatically calls a chain of constructors starting at the top of the class hierarchy and moves down the hierarchy .

    If there were more than two classes in the class hierarchy of the program, the top class default constructor would get called first.

    Here is an example of this:

    class A {
        A() {
        System.out.println("Constructor A");
        }
    }
    
    class B extends A{
    
        public B() {
        System.out.println("Constructor B");
        }
    }
    
    class C extends B{ 
    
        public C() {
        System.out.println("Constructor C");
        }
    
        public static void main(String[] args) {
        C c1 = new C();
        }
    } 
    

    The above would output:

    Constructor A
    Constructor B
    Constructor C
    

提交回复
热议问题