Question

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");
Was it helpful?

Solution

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.

OTHER TIPS

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");

???

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top