子类中的任何构造函数都会调用父类的无参数构造函数(或默认构造函数)。如果在父类中定义了参数化构造函数,则必须使用 super 关键字显式调用父类构造函数,否则会出现编译错误。
class Alpha
{
Alpha(int s, int p)
{
System.out.println("base");
}
}
public class SubAlpha extends Alpha
{
SubAlpha()
{
System.out.println("derived");
}
public static void main(String[] args)
{
new SubAlpha();
}
}
以上代码会报编译错误:
prog.java:13: error: constructor Alpha in class Alpha cannot be applied to given types;
{
^
required: int,int
found: no arguments
reason: actual and formal argument lists differ in length
1 error
发生上述错误是因为我们在父类中没有任何无参数构造函数/默认构造函数,也没有从子类调用参数化构造函数。
现在要解决这个问题,要么像这样调用参数化构造函数:
class Alpha
{
Alpha(int s, int p)
{
System.out.println("base");
}
}
public class SubAlpha extends Alpha
{
SubAlpha()
{
super(4, 5); // calling the parameterized constructor of parent class
System.out.println("derived");
}
public static void main(String[] args)
{
new SubAlpha();
}
}
输出
base
derived
或
在父类中定义一个无参数构造函数,如下所示:
class Alpha
{
Alpha(){
}
Alpha(int s, int p)
{
System.out.println("base");
}
}
public class SubAlpha extends Alpha
{
SubAlpha()
{
System.out.println("derived");
}
public static void main(String[] args)
{
new SubAlpha();
}
}
输出
derived