问题:
Java requires that if you call this() or super() in a constructor, it must be the first statement. Java要求,如果您在构造函数中调用this()或super(),则它必须是第一条语句。 Why? 为什么?
For example: 例如:
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: 但是,您可以通过重新安排一些代码来解决此问题:
public class MySubClass extends MyClass {
public MySubClass(int a, int b) {
super(a + b); // OK
}
}
Here is another example: 这是另一个示例:
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. 这只是在阻止您执行无法包含在单个表达式中的逻辑。
There are similar rules for calling this()
. 调用this()
有类似的规则。 The compiler says "call to this must be first statement in constructor". 编译器说“对此的调用必须是构造函数中的第一条语句”。
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? 您能否举一个代码示例,如果编译器没有此限制,那么会发生不好的事情吗?
解决方案:
参考一: 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
来源:oschina
链接:https://my.oschina.net/u/3797416/blog/4411251