[英]How do I declare a default constructor for sub-class of abstract class?
The following doesn't work for me in Java. 以下内容在Java中对我不起作用。 Eclipse complains that there is no such constructor. Eclipse抱怨没有这样的构造函数。 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");
You can't instantiate Foo
since it's abstract. 由于Foo
是抽象的,因此无法实例化。
Instead, Bar
needs a constructor which calls the super(String)
constructor. 相反, Bar
需要一个构造函数,该构造函数调用super(String)
构造函数。
eg 例如
public Bar(String text) {
super(text);
}
Here I'm passing the text
string through to the super constructor. 在这里,我将text
字符串传递给超级构造函数。 But you could do (for instance): 但是您可以这样做(例如):
public Bar() {
super(DEFAULT_TEXT);
}
The super()
construct needs to be the first statement in the subclass constructor. super()
构造必须是子类构造函数中的第一条语句。
You can't instantiate from an abstract class and that's what you are trying here. 您不能从抽象类实例化,这就是您在这里尝试的方法。 Are you sure that you didn't mean: 您确定您不是故意的:
Bar b = new Bar("hello");
??? ???
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.