Why do this() and super() have to be the first statement in a constructor?

前端 未结 21 1926
北荒
北荒 2020-11-21 23:10

Java requires that if you call this() or super() in a constructor, it must be the first statement. Why?

For example:

public class MyClass {
    publi         


        
21条回答
  •  说谎
    说谎 (楼主)
    2020-11-21 23:45

    It makes sense that constructors complete their execution in order of derivation. Because a superclass has no knowledge of any subclass, any initialization it needs to perform is separate from and possibly prerequisite to any initialization performed by the subclass. Therefore, it must complete its execution first.

    A simple demonstration:

    class A {
        A() {
            System.out.println("Inside A's constructor.");
        }
    }
    
    class B extends A {
        B() {
            System.out.println("Inside B's constructor.");
        }
    }
    
    class C extends B {
        C() {
            System.out.println("Inside C's constructor.");
        }
    }
    
    class CallingCons {
        public static void main(String args[]) {
            C c = new C();
        }
    }
    

    The output from this program is:

    Inside A's constructor
    Inside B's constructor
    Inside C's constructor
    

提交回复
热议问题