1

以下内容在 Java 中对我不起作用。Eclipse 抱怨没有这样的构造函数。我已将构造函数添加到子类以解决它,但是还有另一种方法可以做我想做的事情吗?

public abstract class Foo {
    String mText;

    public Foo(String text) {
        mText = text;
    }  
}

public class Bar extends Foo {

}

Foo foo = new Foo("foo");
4

2 回答 2

10

你不能实例化Foo,因为它是抽象的。

相反,Bar需要一个调用构造函数的super(String)构造函数。

例如

public Bar(String text) {
   super(text);
}

在这里,我将text字符串传递给超级构造函数。但是你可以这样做(例如):

public Bar() {
   super(DEFAULT_TEXT);
}

super()构造必须是子类构造函数中的第一条语句。

于 2010-02-08T21:58:04.247 回答
0

您不能从抽象类实例化,这就是您在这里尝试的。你确定你不是这个意思:

Bar b = new Bar("hello");

???

于 2010-02-08T22:00:24.633 回答