重载包含显式构造函数的类,调用super()(Overloading a class containing an explicit constructor with a call to super (

编程入门 行业动态 更新时间:2024-10-26 12:22:14
重载包含显式构造函数的类,调用super()(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 ( ); } }

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.

更多推荐

本文发布于:2023-07-26 08:12:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1272911.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   Overloading   super   class   constructor

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!