如何为抽象类的子类声明默认构造函数?
以下内容在 Java 中对我不起作用。 Eclipse 抱怨没有这样的构造函数。我已将构造函数添加到子类中以解决它,但是还有其他方法可以完成我想要做的事情吗?
public abstract class Foo {
String mText;
public Foo(String text) {
mText = text;
}
}
public class Bar extends Foo {
}
Foo foo = new Foo("foo");
The following doesn't work for me in Java. Eclipse complains that there is no such constructor. I've added the constructor to the sub-class to get around it, but is there another way to do what I'm trying to do?
public abstract class Foo {
String mText;
public Foo(String text) {
mText = text;
}
}
public class Bar extends Foo {
}
Foo foo = new Foo("foo");
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您无法实例化
Foo
因为它是抽象的。相反,
Bar
需要一个调用super(String)
构造函数的构造函数。例如,
这里我将
text
字符串传递给超级构造函数。但你可以这样做(例如):super()
构造必须是子类构造函数中的第一个语句。You can't instantiate
Foo
since it's abstract.Instead,
Bar
needs a constructor which calls thesuper(String)
constructor.e.g.
Here I'm passing the
text
string through to the super constructor. But you could do (for instance):The
super()
construct needs to be the first statement in the subclass constructor.您无法从抽象类实例化,这就是您在这里尝试的。你确定你不是说:
???
You can't instantiate from an abstract class and that's what you are trying here. Are you sure that you didn't mean:
???