Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
255 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...