"Constructor cannot be applied to given types" when constructors have inheritance

This is my base class:

abstract public class CPU extends GameObject { protected float shiftX; protected float shiftY; public CPU(float x, float y) { super(x, y); } 

and here is one of its subclasses:

 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; } 

The new constructor is highlighted and it says:

 Constructor CPU in class CPU cannot be applied to given types: required: float, float found: no arguments 

How to solve it?

+6
source share
4 answers

As soon as you try to report an error, you need to pass parameters to the constructor of the base class.

Add super(x, y);

+15
source

The target must initialize the superclass using one of its constructors. If there is a default constructor (without a parameter), then the compiler calls it implicitly, otherwise the subclass constructor must call it, using super as the first line of its constructor.

In your case, it will be:

 public Beam(float x, float y, float shiftX, float shiftY, int beamMode) { super(x, y) 

And delete the assignments this.x and this.y later.

Also, avoid creating protected , which makes debugging difficult. Add getters and, if necessary, setters

+4
source

I suspect you should write

 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 } 

and

 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); } } 
+2
source

If you do not specify a default constructor, and at compile time it will give you this error, "the constructor in the class cannot be applied to the specified type"; Note. If you have created any parameterized constructor.

0
source

All Articles