Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (10.2k points)

I was wondering why in java constructors are not inherited? You know when you have a class like this:

public class Super {

  public Super(ServiceA serviceA, ServiceB serviceB, ServiceC serviceC){

    this.serviceA = serviceA;

    //etc

  } 

}

Later when you inherit from Super, java will complain that there is no default constructor defined. The solution is obviously something like:

public class Son extends Super{

  public Son(ServiceA serviceA, ServiceB serviceB, ServiceC serviceC){

    super(serviceA,serviceB,serviceC);

  }

}

This code is repetitive, not DRY and useless (IMHO)... so that brings the question again:

Why java doesn't support constructor inheritance? Is there any benefit in not allowing this inheritance?

1 Answer

0 votes
by (46k points)

When you inherit from Super this is what in reality happens:

public class Son extends Super{

  // If you dont declare a constructor of any type, adefault one will appear.

  public Son(){

    // If you dont call any other constructor in the first line a call to super() will be placed instead.

    super();

  }

}

So, that is the reason, because you have to call your unique constructor, since"Super" doesn't have a default one.

Now, trying to guess why Java doesn't support constructor inheritance, probably because a constructor only makes sense if it's talking about concrete instances, and you shouldn't be able to create an instance of something when you don't know how it's defined (by polymorphism).

Related questions

Browse Categories

...