Can I Avoid Implementing Parameterized Constructors in Sub classes

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*/ }
Jon Skeet
people
quotationmark

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.

people

See more on this question at Stackoverflow