2010-02-08 44 views
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"); 

回答

10

您不能實例化Foo,因爲它是抽象的。

取而代之,Bar需要一個構造函數,它調用構造函數super(String)

例如

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

在這裏,我將text字符串傳遞給超級構造函數。但你可以(比如)做:

public Bar() { 
    super(DEFAULT_TEXT); 
} 

super()結構需要在子類構造函數的第一個語句。

+0

+1你的回答比較好:P – 2010-02-08 22:00:45

+0

謝謝。我的意思是 酒吧酒吧=新酒吧(「酒吧」); 我有你的解決方案實現,但我不知道你是否有實現Java構造函數。 – 2010-02-09 00:30:05

0

你不能從抽象類實例化,這就是你在這裏嘗試的。您確定您的意思不是:

Bar b = new Bar("hello"); 

???