views:

72

answers:

2

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");
+9  A: 

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.

Brian Agnew
+1 your answer is better :P
Alberto Zaccagni
Thanks. I meant Bar bar = new Bar("bar");I have you solution implemented, but I wasn't sure if you HAD to implement the constructor in Java.
Michael Pardo
A: 

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

???

aefxx