为何this()和super()必须是构造函数中的第一条语句?

问题:

Java requires that if you call this() or super() in a constructor, it must be the first statement. Java要求,若是您在构造函数中调用this()或super(),则它必须是第一条语句。 Why? 为何? express

For example: 例如: app

public class MyClass {
    public MyClass(int x) {}
}

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

The Sun compiler says "call to super must be first statement in constructor". Sun编译器说“对super的调用必须是构造函数中的第一条语句”。 The Eclipse compiler says "Constructor call must be the first statement in a constructor". Eclipse编译器说“构造函数调用必须是构造函数中的第一条语句”。 函数

However, you can get around this by re-arranging the code a little bit: 可是,您能够经过从新安排一些代码来解决此问题: ui

public class MySubClass extends MyClass {
    public MySubClass(int a, int b) {
        super(a + b);  // OK
    }
}

Here is another example: 这是另外一个示例: this

public class MyClass {
    public MyClass(List list) {}
}

public class MySubClassA extends MyClass {
    public MySubClassA(Object item) {
        // Create a list that contains the item, and pass the list to super
        List list = new ArrayList();
        list.add(item);
        super(list);  // COMPILE ERROR
    }
}

public class MySubClassB extends MyClass {
    public MySubClassB(Object item) {
        // Create a list that contains the item, and pass the list to super
        super(Arrays.asList(new Object[] { item }));  // OK
    }
}

So, it is not stopping you from executing logic before the call to super. 所以,这不会阻止您在调用super以前执行逻辑 It is just stopping you from executing logic that you can't fit into a single expression. 这只是在阻止您执行没法包含在单个表达式中的逻辑。 spa

There are similar rules for calling this() . 调用this()有相似的规则。 The compiler says "call to this must be first statement in constructor". 编译器说“对此的调用必须是构造函数中的第一条语句”。 .net

Why does the compiler have these restrictions? 为何编译器有这些限制? Can you give a code example where, if the compiler did not have this restriction, something bad would happen? 您可否举一个代码示例,若是编译器没有此限制,那么会发生很差的事情吗? rest


解决方案:

参考一: https://stackoom.com/question/4twH/为何this-和super-必须是构造函数中的第一条语句
参考二: https://oldbug.net/q/4twH/Why-do-this-and-super-have-to-be-the-first-statement-in-a-constructor
相关文章
相关标签/搜索