当构造函数具有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.xthis.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); } } 

如果你没有指定任何默认构造函数,那么在编译时它会给你这个错误“类中的构造函数不能应用于给定的类型;” 注意:如果您创建了任何参数化构造函数。