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

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

    I found a woraround.

    This won't compile :

    public class MySubClass extends MyClass {
        public MySubClass(int a, int b) {
            int c = a + b;
            super(c);  // COMPILE ERROR
            doSomething(c);
            doSomething2(a);
            doSomething3(b);
        }
    }
    

    This works :

    public class MySubClass extends MyClass {
        public MySubClass(int a, int b) {
            this(a + b);
            doSomething2(a);
            doSomething3(b);
        }
    
        private MySubClass(int c) {
            super(c);
            doSomething(c);
        }
    }
    

提交回复
热议问题