Can constructors be inherited?
Solution and explanation
Answer
No. Constructors are not inherited and cannot be overridden. A subclass must declare its own constructors, and each one calls a parent constructor with super(...).
class Vehicle {
Vehicle(String regNo) { }
}
class Bike extends Vehicle {
// No constructor declared: the compiler adds Bike() { super(); }
// But Vehicle has no no-arg constructor → compile error.
}
class Car extends Vehicle {
Car(String regNo) { super(regNo); } // correct: declare and chain
}
new Car("DL3C1234"); // fine
// new Car(); // error: Car has no no-arg constructor even though Vehicle might
Why not inherited?
- A constructor's name is its class name; a parent constructor named
Vehiclemakes no sense for creating aCar. - A subclass usually has extra fields that the parent constructor knows nothing about, so inheriting it would create partially initialised objects.
Related facts
- Constructors cannot be overridden, so there is no runtime polymorphism for constructors.
- They can be overloaded within a class.
- Records and Lombok (
@AllArgsConstructor,@RequiredArgsConstructor) generate constructors to reduce boilerplate.
