java即使我不在子类中调用super(),程序也会抛出错误,因为必须定义一个显式构造函数
这里我调用基类的参数化构造函数,但当我没有在基类中给出默认构造函数时,它会抛出错误,为什么会这样,因为我没有调用super()
class Base {
int num;
// if i didnt give this default constructor then throws error
// Base(){}
Base(int a)
{
num=a;
}
int getnum()
{
return num;
}
}
class sub1 extends Base{
sub1(){
super(5); // im not calling super();
}
}
class Sub2 extends Base{
public static void main(String[] args) {
}
}
# 1 楼答案
当您用参数重写具有构造函数的类时,必须调用该构造函数。如果超类有多个带参数的构造函数,则必须至少调用其中的一个
实际上,你在sub1中调用super,但不是sub2。当提到构造函数时,定义如下
其中调用超级方法是