似乎如果程序员提供了构造函数,并且使用了对super()的调用,则不能在该类中调用其他构造函数(即它不能被重载).这是Java固有的正常行为吗?为什么?
abstract class Four {
Four ( ) { }
Four (int x) { }
}
class Three extends Four {
public Three ( String name) { }
Three (int t, int y) { }
}
class Two extends Three {
Two ( ) { super ( "number"); }
// Two (int t, int y) { } //causes an error when uncommented
}
class One extends Two {
public static void main (String [ ] args) {
new One ( );
}
}
Run Code Online (Sandbox Code Playgroud)
在该类中不能调用其他构造函数(即它不能被重载).
这根本不是真的.Two(int t, int y)构造函数的问题在于它没有显式链接到任何构造函数,这意味着存在一个隐式super()调用 - 由于Three1中没有无参数构造函数而失败.您可以通过两种方式解决这个问题:
直接链接到超级构造函数
Two (int t, int y) {
super("number");
}
Run Code Online (Sandbox Code Playgroud)链接到同一个类中的构造函数
Two (int t, int y) {
this();
}
Run Code Online (Sandbox Code Playgroud)1它不必是无参数的,严格来说 - 如果你添加一个Three(String... values)构造函数,那没关系.您需要有一个可以使用空参数列表调用的构造函数.
| 归档时间: |
|
| 查看次数: |
75 次 |
| 最近记录: |