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*/ }
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'sfinal
modifier).