[英]“Constructor cannot be applied to given types” when constructors have inheritance
这是我的基类:
abstract public class CPU extends GameObject {
protected float shiftX;
protected float shiftY;
public CPU(float x, float y) {
super(x, y);
}
这是它的子类之一:
public class Beam extends CPU {
public Beam(float x, float y, float shiftX, float shiftY, int beamMode) {
try {
image = ImageIO.read(new File("/home/tab/Pictures/Beam"+beamMode+".gif"));
} catch (Exception e) {
e.printStackTrace();
}
this.x = x;
this.y = y;
this.shiftX = shiftX;
this.shiftY = shiftY;
}
New构造函数突出显示,它说:
Constructor CPU in class CPU cannot be applied to given types:
required: float, float
found: no arguments
怎么解决呢?
当错误试图告诉您时,您需要将参数传递给基类的构造函数。
加super(x, y);
最终对象需要使用其构造函数之一来初始化超类。 如果存在默认(无参数)构造函数,则编译器将隐式调用它,否则子类构造函数需要使用super
作为其构造函数的第一行来调用它。
您的情况是:
public Beam(float x, float y, float shiftX, float shiftY, int beamMode) {
super(x, y)
并在以后删除对this.x
和this.y
的分配。
另外,避免使它们protected
,使其难以调试。 而是添加getters
,如果绝对必要的话,添加setters
我怀疑你应该写
protected float shiftX;
protected float shiftY;
public CPU(float x, float y, float shiftX, float shiftY) {
super(x, y);
this.shiftX = shiftX;
this.shiftY = shiftY
}
和
public Beam(float x, float y, float shiftX, float shiftY, int beamMode) {
super(x,y,shiftX,shiftY);
try {
image = ImageIO.read(new File("/home/tab/Pictures/Beam"+beamMode+".gif"));
} catch (Exception e) {
throw new AssertionError(e);
}
}
如果您未指定任何默认构造函数,则在编译时会出现此错误“类中的构造函数无法应用于给定类型;” 注意:如果创建了任何参数化的构造函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.