开发者

How do I declare a default constructor for sub-class of abstract class?

开发者 https://www.devze.com 2022-12-19 08:24 出处:网络
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

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 exten开发者_开发问答ds Foo {

}

Foo foo = new Foo("foo");


You can't instantiate Foo since it's abstract.

Instead, Bar needs a constructor which calls the super(String) constructor.

e.g.

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

Here I'm passing the text string through to the super constructor. But you could do (for instance):

public Bar() {
   super(DEFAULT_TEXT);
}

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:

Bar b = new Bar("hello");

???

0

精彩评论

暂无评论...
验证码 换一张
取 消