Understanding Constructor Inheritance in Java
Despite popular expectations, constructors are not inherited in Java. This design decision has sparked curiosity and questions among developers.
Reasons for Non-Inheritance of Constructors
Consider the following example:
public class Super { public Super(ServiceA serviceA, ServiceB serviceB, ServiceC serviceC){ this.serviceA = serviceA; //etc } }
If constructors were inherited, every class, including those ultimately derived from Object, would possess a parameterless constructor. This would pose a logical dilemma, especially in cases like:
FileInputStream stream = new FileInputStream();
What action should this line perform without any specified parameters?
Advantages of Non-Inheritance
The absence of constructor inheritance ensures that subclasses require specific parameters for instantiation, which may vary from those required by their superclass. This prevents unintended or inconsistent behavior when creating objects.
Alternative Solution
To address the repetition and DRY concerns, Java allows for the creation of explicit "pass-through" constructors in subclasses that forward parameters to the superclass constructor as follows:
public class Son extends Super{ public Son(ServiceA serviceA, ServiceB serviceB, ServiceC serviceC){ super(serviceA,serviceB,serviceC); } }
While this approach adds some redundancy, it prioritizes clarity and control over object instantiation, effectively replacing the non-existing inherited constructors.
The above is the detailed content of Why Are Constructors Not Inherited in Java?. For more information, please follow other related articles on the PHP Chinese website!