[英]Overloading a class containing an explicit constructor with a call to super ( )
看来,如果使用程序员提供的构造函数并调用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 ( );
}
}
在该类中不能调用其他构造函数(即,不能重载)。
那根本不是真的。 您的Two(int t, int y)
构造函数的问题在于它没有显式链接到任何构造函数,这意味着存在一个隐式的super()
调用-失败,因为在Three
1中没有无参数的构造函数。 您可以通过两种方式解决此问题:
直接链接到超级构造函数
Two (int t, int y) { super("number"); }
链接到同一类中的构造函数
Two (int t, int y) { this(); }
1严格来说,它不必是无参数的-如果您添加Three(String... values)
构造函数,那就可以了。 您需要有一个可以用空参数列表调用的构造函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.