Home > Java > javaTutorial > Why Are Constructors Not Inherited in Java?

Why Are Constructors Not Inherited in Java?

Barbara Streisand
Release: 2024-11-29 22:39:11
Original
796 people have browsed it

Why Are Constructors Not Inherited in Java?

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
  } 
}
Copy after login

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();
Copy after login

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);
  }
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template