In Java, a class's constructors are not inherited by its subclasses. This design choice has sparked a longstanding question: why does Java take this approach?
Consider the following class:
public class Super { public Super(ServiceA serviceA, ServiceB serviceB, ServiceC serviceC){ this.serviceA = serviceA; //etc } }
When a subclass, Son, inherits from Super, Java demands that a constructor be explicitly declared in Son with parameters identical to those in Super. This can lead to repetitive code, as demonstrated below:
public class Son extends Super{ public Son(ServiceA serviceA, ServiceB serviceB, ServiceC serviceC){ super(serviceA,serviceB,serviceC); } }
This repetition prompts the question: why does Java forbid the inheritance of constructors?
The answer lies in the potential consequences of such inheritance. If constructors were inherited, every class would eventually inherit a constructor from the base class Object. This would mean that every class, regardless of its purpose, would have a parameterless constructor.
Such a design would create ambiguity. For instance, the following code:
FileInputStream stream = new FileInputStream();
would leave in question what parameters should be passed to the constructor. Different classes might require different parameters, making such inheritance highly impractical.
While there are scenarios where pass-through constructors (constructors that simply call the superclass constructor) are useful, Java wisely chose not to make this the default behavior. The varying parameters required for subclass construction necessitate the explicit declaration of constructors in each class.
The above is the detailed content of Why Doesn't Java Inherit Constructors?. For more information, please follow other related articles on the PHP Chinese website!