[英]Overloading a class containing an explicit constructor with a call to super ( )
It appears that if a programmer supplied constructor, with a call to super ( ) is used, no other constructor can be invoked in that class ( ie it can't be overloaded). 看来,如果使用程序员提供的构造函数并调用super(),则该类中不能调用其他构造函数(即,不能重载)。 Is this normal behavior that is inherent to Java?
这是Java固有的正常行为吗? Why?
为什么?
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 ( );
}
}
no other constructor can be invoked in that class ( ie it can't be overloaded).
在该类中不能调用其他构造函数(即,不能重载)。
That's not true at all. 那根本不是真的。 The problem with your
Two(int t, int y)
constructor is that it doesn't chain to any constructor explicitly, meaning that there's an implicit super()
call - which fails as there are no parameterless constructors in Three
1 . 您的
Two(int t, int y)
构造函数的问题在于它没有显式链接到任何构造函数,这意味着存在一个隐式的super()
调用-失败,因为在Three
1中没有无参数的构造函数。 You can fix that in two ways: 您可以通过两种方式解决此问题:
Chain directly to a super constructor 直接链接到超级构造函数
Two (int t, int y) { super("number"); }
Chain to a constructor in the same class 链接到同一类中的构造函数
Two (int t, int y) { this(); }
1 It doesn't have to be parameterless, strictly - if you add a Three(String... values)
constructor, that's okay. 1严格来说,它不必是无参数的-如果您添加
Three(String... values)
构造函数,那就可以了。 You need to have a constructor that can be invoked with an empty argument list. 您需要有一个可以用空参数列表调用的构造函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.