为什么必须在 java 的 subclass 的参数化构造函数中调用 Super class 的参数化构造函数?
Why is it mandatory to call a Super class's parameterized constructor inside subclass's parameterized constructor in java?
下面的代码编译失败:
class Super
{
int i = 0;
Super(String text)
{
i = 1;
}
}
class Sub extends Super
{
Sub(String text)
{
------------LINE 14------------
i = 2;
}
public static void main(String args[])
{
Sub sub = new Sub("Hello");
System.out.println(sub.i);
}
}
但是当我在第 14 行添加 super(text)
时,它工作正常。为什么会这样?
没有显式调用超级 class 构造函数的构造函数将被添加到无参数构造函数的隐式调用(就好像 super();
语句被添加到它的第一个语句).
在你的例子中,由于superclass有一个带参数的构造函数,它没有无参数构造函数,所以super();
无法通过编译,你必须调用super(text)
明确地。
因为需要创建 'Super' 对象才能创建 'Sub' 对象。如果您没有任何空的(默认)c'tor,则必须使用现有的 c'tor 之一。
下面的代码编译失败:
class Super
{
int i = 0;
Super(String text)
{
i = 1;
}
}
class Sub extends Super
{
Sub(String text)
{
------------LINE 14------------
i = 2;
}
public static void main(String args[])
{
Sub sub = new Sub("Hello");
System.out.println(sub.i);
}
}
但是当我在第 14 行添加 super(text)
时,它工作正常。为什么会这样?
没有显式调用超级 class 构造函数的构造函数将被添加到无参数构造函数的隐式调用(就好像 super();
语句被添加到它的第一个语句).
在你的例子中,由于superclass有一个带参数的构造函数,它没有无参数构造函数,所以super();
无法通过编译,你必须调用super(text)
明确地。
因为需要创建 'Super' 对象才能创建 'Sub' 对象。如果您没有任何空的(默认)c'tor,则必须使用现有的 c'tor 之一。