问题描述
在子类中,我们可以使用子类的构造函数初始化数据成员,该构造函数在内部调用超类的构造函数super()
.如果子类不能从其超类继承构造函数,那么 super()
调用如何初始化超类?
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?
推荐答案
来自子类的构造函数可以调用来自超类的构造函数,但它们不会被继承.
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);
}
}
那么你不能写:
new Sub(10);
因为没有 Sub(int)
构造函数.
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.
构造函数声明不是成员.它们永远不会被继承,因此不会被隐藏或覆盖.
这篇关于子类是否从它的超类继承构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!