java中带继承的构造函数
甲级 B类java中带继承的构造函数,java,inheritance,Java,Inheritance,甲级 B类 class A { int a; int c; A (int a, int c) { this.a = a; this.c = c; } } 当我编译代码时,它显示了这个错误 class B extends A{ public static void main (String [] args) { A obj = new A (5, 6); } } 这个错误什么时候出现?当继
class A {
int a;
int c;
A (int a, int c) {
this.a = a;
this.c = c;
}
}
当我编译代码时,它显示了这个错误
class B extends A{
public static void main (String [] args) {
A obj = new A (5, 6);
}
}
这个错误什么时候出现?当继承类为时,构造函数必须是同一类型的超类?向类B添加构造函数
编译器意识到您不能实例化类B 向类B添加构造函数 编译器意识到您不能实例化类B A指定一个包含两个参数的构造函数,B仅指定一个无参数的构造函数(默认值) 如果您真的想让B从A继承,您还需要创建一个构造函数,或者一个也有两个参数,或者一个只是用默认值调用A的构造函数:
B.java:1: error: constructor A in class A cannot be applied to given types;
class B extends A{
^
required: int,int
found: no arguments
reason: actual and formal argument lists differ in length
1 error
但是,如果您只想在main中实例化A,那么从代码中,B不需要从A继承。在这种情况下,只需删除继承。A指定一个包含两个参数的构造函数,B仅指定一个无参数的默认构造函数
如果您真的想让B从A继承,您还需要创建一个构造函数,或者一个也有两个参数,或者一个只是用默认值调用A的构造函数:
B.java:1: error: constructor A in class A cannot be applied to given types;
class B extends A{
^
required: int,int
found: no arguments
reason: actual and formal argument lists differ in length
1 error
但是,如果您只想在main中实例化A,那么从代码中,B不需要从A继承。在这种情况下,只需删除继承即可