Can I Avoid Implementing Parameterized Constructors in Sub-classes

197 views Asked by At

I have an abstract class with a 1-param constructor which should be identical for any concrete sub-class. Does every concrete sub-class have to have that same 1-param constructor, and if so, why?

Abstract:

public abstract class AbstractClass {

public AbstractClass(String name){}

public AbstractClass getConcreteClass(){
    return (AbstractClass) new ConcreteClass("name");   //Does not work
}

}

Concrete:

public class ConcreteClass { /*Would like to have no constructor*/ }
3

There are 3 answers

1
SirRichie On BEST ANSWER

Each class must have at least one constructor. In classes without an explicit constructor, there is the implicit constructor without any arguments and without any special initialization.

If your parent class declares a constructor, children cannot use an implicit constructor, because the parent class basically indicates "I cannot be instantiated implicitly", so to provide the necessary information, the child classes must also declare at least one explicit constructor.

Also, automatic copying of constructors would violate abstractions and information hiding, as your child class might unwillingly expose constructors to callers which it does not want to expose.

Of course you could argue that this should be the default and if I do not want a constructor to be exposed I could deliberately indicate this. However, Java decided to go the other way. A similar discussion is that on method overriding: do I have to allow a method to be overridden in my parent class (e.g., C#'s virtual modifier) or do I simply forbid it for certain methods (Java's final modifier).

0
sp00m On

You can use a nullary constructor if you instantiate the expected parameter within your subcontroller:

public class ConcreteClass extends AbstractClass {
    public ConcreteClass() {
        super("concrete");
    }
}

You cannot provide no constructor though.

0
Jon Skeet On

Does every concrete sub-class have to have that same 1-param constructor

Well, strictly speaking they don't have to have that constructor - but they'll need to have a constructor, in order to pass a value to the AbstractClass constructor.

and if so, why?

Because constructors aren't inherited. The information required for a subclass often isn't the same as the information required for a superclass.

Imagine if constructors were inherited - then everything would have a parameterless constructor, because Object does. So you'd be able to write:

FileInputStream stream = new FileInputStream();

... what would that mean?

Bottom line: add the constructors to your subclasses. It's only three lines per subclass... that shouldn't be an issue.