Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does a subclass inherit constructors from it super class?

Tags:

In a subclass we can initialize data members using the subclass's constructor which internally calls the superclass's constructor super(). If a subclass can't inherit constructors from its superclass then how can the super() call initialize the superclass?

like image 948
AmitSource Avatar asked Mar 04 '11 12:03

AmitSource


People also ask

Can you call a sub class constructor from super class constructor?

3. Use of super() to access superclass constructor. As we know, when an object of a class is created, its default constructor is automatically called. To explicitly call the superclass constructor from the subclass constructor, we use super() .

Does a subclass automatically call the superclass constructor?

The constructors of the subclass can initialize only the instance variables of the subclass. Thus, when a subclass object is instantiated the subclass object must also automatically execute one of the constructors of the superclass. To call a superclass constructor the super keyword is used.

How do you inherit a constructor from a superclass to a subclass in Java?

Constructors are not inherited, you must create a new, identically prototyped constructor in the subclass that maps to its matching constructor in the superclass. Even as a non-n00b Java programmer, that's unclear to me.

Does a subclass need its own constructor?

A subclass needs a constructor if the superclass does not have a default constructor (or has one that is not accessible to the subclass). If the subclass has no constructor at all, the compiler will automatically create a public constructor that simply calls through to the default constructor of the superclass.


1 Answers

A constructor from a subclass can call constructors from the superclass, but they're not inherited as such.

To be clear, that means if you have something like:

public class Super {     public Super(int x)     {     } }  public class Sub extends Super {     public Sub()     {         super(5);     } } 

then you can't write:

new Sub(10); 

because there's no Sub(int) constructor.

It may be helpful to think of constructors as uninherited static methods with an implicit parameter of the object being initialized.

From the Java Language Spec, section 8.8:

Constructor declarations are not members. They are never inherited and therefore are not subject to hiding or overriding.

like image 84
Jon Skeet Avatar answered Oct 28 '22 03:10

Jon Skeet