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?
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() .
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With