开发者

Does a subclass inherit constructors from it super class?

In a subclass we can initialize data members using the subclass's const开发者_C百科ructor 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?


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.


No a subclass cannot inherit the constructors of its superclass.

Constructors are special function members of a class in that they are not inherited by the subclass. Constructors are used to give a valid state for an object at creation.

One of the main reasons is because you probably don't want to overide the superclasses constructor, which would be possible if they were inherited. By giving the developer the ability to override a superclasses constructor you would erode the encapsulation abilities of the language.

See also : Constructors are never inherited


super is a Java keyword for referring to the superclass, and super() is the way to call your superclass's constructor. The constructor is not inherited but you are still able to call it.


No..Not at all never...A Subclass Does not inherits its Superclass constructor..instead it call it can call its Superclass Constructor Using keyword "super()"...


First of all, constructors are not members of classes, and only members are inherited.

Second, we can imagine cases for which we don't want subclasses to have the same constructors than the parent class.

Imagine an abstract class Vehicle with a constructor Vehicle(int wheels), and a subclass Bicycle.

By definition, a Bicycle has 2 wheels so we can imagine that Bicycle constructor will call super(2) and isn't it better in this case that Bicycle does not expose a constructor Bicycle(int wheels) ?


public class Super
{
    public Super(int x)
    {
    }
}

public class Sub extends Super
{
    public Sub(int x)
    {
        super(x); // call constructor from Super class 
    }
}
Sub obj = new Sub(5);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜