超类中没有可用的构造函数(Java)

时间:2017-10-07 13:05:56

标签: java

我有一个超级类,它叫游戏。它看起来像这样:

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

}

主要关注的是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();
   }
}

Tower子类的子类叫做Catapult:

public class Catapult extends Tower {
    public Catapult(){
        super(5,3);
    }

}

我是Java的新手,看不出我在这里做错了什么。为什么我需要游戏中Tower的默认构造函数?

1 个答案:

答案 0 :(得分:1)

您需要在Game类中显式声明默认构造函数。

public Game (){} 

因为Object实例化在此期间链接到Object类,它将调用其超类构造函数。您已在Game中显式声明了arg-constructor,因此不会自动添加默认构造函数。