[英]There is no available constructor in the superclass (Java)
I have one super class, which called game that.我有一个超级课程,叫做游戏。 It looks like this:
它看起来像这样:
import java.util.ArrayList;
public class Game {
private ArrayList<Enemy> enemies = new ArrayList<Enemy>();
private ArrayList<Tower> towers = new ArrayList<Tower>();
private int corridorLength;
private int currentPosition = 0;
public Game(int corridorLength){
this.corridorLength = corridorLength;
}
public void addTower(int damage,int timeStep){
this.towers.add(new Tower(damage,timeStep)); // Add tower with
current position corrdor length
}
public void addEnemy(int health, int speed){
this.enemies.add(new Enemy(health,speed));
}
public void advance(){
this.currentPosition = this.currentPosition + 1;
if(this.currentPosition == this.corridorLength){
System.out.println("Game Over");
}
}
public void printDamage(){
System.out.println(this.towers.get(this.currentPosition));
}
}
The main focus is on the public void addTower(int, int) So, I have a subclass called Tower:主要关注的是 public void addTower(int, int) 所以,我有一个名为 Tower 的子类:
public class Tower extends Game {
public Tower(int damage, int timeStep){
super.addTower(damage,timeStep);
}
public void getDamage(){
super.printDamage();
}
}
And subclass of the Tower subclass called Catapult:以及名为 Catapult 的 Tower 子类的子类:
public class Catapult extends Tower {
public Catapult(){
super(5,3);
}
}
I am new to Java and can't see what am I doing wrong here.我是 Java 新手,看不出我在这里做错了什么。 Why do I need a default constructor for the Tower in the Game?
为什么我需要游戏中的塔的默认构造函数?
You need to explicitly declare default constructor in Game
class.您需要在
Game
类中显式声明默认构造函数。
public Game (){}
Since, Object
instantiation chained to Object
class during that, it will call its super class constructor.由于在此期间
Object
实例化链接到Object
类,因此它将调用其超类构造函数。 You have explicitly declared arg-constructor in Game
, so default constructor won't be added automatically.您已在
Game
显式声明 arg-constructor ,因此不会自动添加默认构造函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.