I have a some simple Java code that looks similar to this in its structure:
abstract public class BaseClass {
String someString;
public BaseClass(String someString) {
this.someString = someString;
}
abstract public String getName();
}
public class ACSubClass extends BaseClass {
public ASubClass(String someString) {
super(someString);
}
public String getName() {
return "name value for ASubClass";
}
}
I will have quite a few subclasses of BaseClass
, each implementing the getName()
method in its own way (template method pattern).
This works well, but I don't like having the redundant constructor in the subclasses. It's more to type and it is difficult to maintain. If I were to change the method signature of the BaseClass
constructor, I would have to change all the subclasses.
When I remove the constructor from the subclasses, I get this compile-time error:
Implicit super constructor BaseClass() is undefined for default constructor. Must define an explicit constructor
Is what I am trying to do possible?
You get this error because a class which has no constructor has a default constructor, which is argument-less and is equivalent to the following code:
public ACSubClass() {
super();
}
However since your BaseClass declares a constructor (and therefore doesn't have the default, no-arg constructor that the compiler would otherwise provide) this is illegal - a class that extends BaseClass can't call super();
because there is not a no-argument constructor in BaseClass.
This is probably a little counter-intuitive because you might think that a subclass automatically has any constructor that the base class has.
The simplest way around this is for the base class to not declare a constructor (and thus have the default, no-arg constructor) or have a declared no-arg constructor (either by itself or alongside any other constructors). But often this approach can't be applied - because you need whatever arguments are being passed into the constructor to construct a legit instance of the class.