当您定义自己的构造函数时,java编译器不再自动插入默认构造函数。
在你的代码中,当构造B时,第一行隐式调用超类构造器。尽管由于您已经重写了A的默认构造方法,因此编译器不会自动使用必要参数自动调用超类构造函数,所以不存在构造函数调用。您应该在B构造函数的第一行添加一行,以便使用它需要的int参数调用A的超类构造函数,或者为A定义构造函数,类似于不带参数的默认构造函数。
您可以重载构造函数,以便一个构造函数像默认构造函数一样是无参数的,然后有其他构造函数接受参数。 :d
这方面的一个例子如下,根据您的代码:
class A
{
private int a;
A(int a)
{
this.a =a;
System.out.println("This is constructor of class A");
}
//overload constructor with parameterless constructor similar to default
A() {
System.out.println("this is like a default no-args constructor");
}
} // end class A
class B extends A
{
private int b;
private double c;
// add in another constructor for B that callers can use
B() {
int b = 9;
System.out.println("new B made in parameterless constructor");
}
B(int b,double c)
{
super(b); // this calls class A's constructor that takes an int argument :D
this.b=b;
this.c=c;
System.out.println("This is constructor of class B");
}
} // end class B
这是基本的基本Java 101,在这里发布之前,您应该努力学习使用教程和其他资源。请阅读[FAQ]和[Ask]了解StackOverflow的用途和范围。提示:它的目的是作为解决实际问题的长期资源,而不是获得基本的教程指导。关于SO的问题和答案旨在对未来的搜索者有用,因此复制这种类型的信息几乎没有长期价值。 –