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

前端 未结 21 1905
北荒
北荒 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:27

    You can use anonymous initializer blocks to initialize fields in the child before calling it's constructor. This example will demonstrate :

    public class Test {
        public static void main(String[] args) {
            new Child();
        }
    }
    
    class Parent {
        public Parent() {
            System.out.println("In parent");
        }
    }
    
    class Child extends Parent {
    
        {
            System.out.println("In initializer");
        }
    
        public Child() {
            super();
            System.out.println("In child");
        }
    }
    

    This will output :

    In parent
    In initializer
    In child

提交回复
热议问题