下面的代码是一个测试程序。为什么我不能在这个程序中使用 A(int a)?
public class A {
int a;
void meth(int b) {
a+=b;
}
A(int a) {
this.a=a;
}
}
class B extends A {
int a;
void meh2(int b) {
a+=b;
}
}
为什么不能向构造函数传递参数?到底是什么原因呢? Netbeans 错误消息:
类 tma1.A 中的构造函数 A 不能应用于给定类型; 必需:整数 发现:没有参数 原因:实际参数列表和形式参数列表的长度不同
最佳答案
在B类中,你需要构造函数。如果你的意思是你不能从B调用A,那只是因为你扩展了A类,所以你需要使用super,它指的是父类(super class)。例如 B 可以是:
class B extends A {
B(int a) {
//You can put additional code here
// This calls the constructor of A
super(a);
//You can put additional code here
}
int a;
void meh2(int b) {
a+=b;
}
}
否则,如果您没有在代码中省略某些内容,则需要为 B 类中的变量 a 分配一些内容
关于父类(super class)中的java构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8130628/