子类构造函数对默认构造函数的java隐式调用
当我试图创建类型B的对象时,下面的代码给出了一个错误。我的问题是,为什么不调用A的默认构造函数
class A
{
private int a;
A(int a)
{
this.a = a;
System.out.println("This is constructor of class A");
}
}
class B extends A
{
private int b;
private double c;
B(int b, double c)
{
this.b = b;
this.c = c;
System.out.println("This is constructor of class B");
}
}
# 1 楼答案
因为,只有当Java中没有构造函数时,才会调用默认构造函数
# 2 楼答案
定义自己的构造函数时,java编译器不再自动插入默认构造函数
在构造B的代码中,在第一行有一个对超级类构造函数的隐式调用
super();
尽管如此,由于您已经重写了的默认构造函数,没有任何构造函数调用会起作用,因为编译器不会用必要的参数自动调用超类构造函数。您应该在B构造函数的第一行添加一行,以使用所需的int参数调用a的超类构造函数,或者为a定义一个类似于不带参数的默认构造函数的构造函数可以重载构造函数,使一个构造函数像默认构造函数一样没有参数,然后让其他构造函数接受参数:D
根据您的代码,这方面的示例如下:
# 3 楼答案
A的默认构造函数将意味着新的A()。您没有可用的构造函数,这意味着构造A的唯一方法是调用新的A(int)。由于没有默认构造函数,B必须显式调用A的超级构造函数来正确初始化A
# 4 楼答案
尝试添加引用超级类构造函数的扩展类构造函数,即
# 5 楼答案
默认构造函数是不包含任何参数的构造函数。如果没有这样的默认构造函数,编译器将创建一个,前提是没有任何其他可用的参数化构造函数
在本例中,由于有一个参数化构造函数可用,编译器不会创建默认构造函数。由于没有可用的默认/无参数构造函数,因此会导致编译错误
# 6 楼答案
因为没有。当您提供自己的参数化构造函数时,编译器不会添加默认构造函数。因此,您似乎认为有0-arg构造函数的类
A
没有任何构造函数。你必须明确地添加一个