看来,如果程序员提供了构造函数,并且使用了对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 ( ); } }It appears that if a programmer supplied constructor, with a call to super ( ) is used, no other constructor can be invoked in that class ( i.e. it can't be overloaded). Is this normal behavior that is inherent to 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 ( ); } }最满意答案
在该类中不能调用其他构造函数(即它不能被重载)。
这根本不是真的。 你的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)构造函数,那没关系。 您需要有一个可以使用空参数列表调用的构造函数。
no other constructor can be invoked in that class ( i.e. 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 Three1. 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. You need to have a constructor that can be invoked with an empty argument list.
更多推荐
发布评论