Java调用构造函数

标签 java constructor call

我创建了一个测试项目,但遇到了一些我无法弄清楚的问题。

我正在尝试在 FightManager 中调用 Monster。我希望怪物的变量(namehealthdamagedefense)等于任何随机怪物( WolfMonsterGoblinMonster)

以前我只有一个怪物,我成功做到了,但现在有 2 个怪物,如果选择了不同的怪物,我如何向变量传递不同的值?

public class Units {
    int health;
    int damage;
    int defense;
    String name;

    public boolean isAlive(){
        if(health >= 1){
            return true;
        }else{
            return false;
        }
    }
}

public class Monster extends Units{
    public Monster(String name,int health,int damage,int defense){
        this.name = name;
        this.health = health;
        this.damage = damage;
        this.defense = defense;
    }
}

public class GoblinMonster extends Monster {
    public GoblinMonster(String name, int health, int damage, int defense) {
        super("Goblin",50,5,6);
        this.name = name;
        this.health = health;
        this.damage = damage;
        this.defense = defense;
    }
}

public class WolfMonster extends Monster {
    public WolfMonster(String name, int health, int damage, int defense) {
        super("Wolf",50,5,6);
        this.name = name;
        this.health = health;
        this.damage = damage;
        this.defense = defense;
    }
}

public class FightManager {

    GameManager manage = new GameManager();
    Player player = new Player("Player",100,10,5);
    GoblinMonster gobli = new GoblinMonster("Goblin", 40, 7, 4);
    WolfMonster wolf = new WolfMonster("Wolf",50,9,6);

    boolean myTurn = true;
    ....

我想知道如何根据生成的怪物来分配怪物的值。

最佳答案

我认为这里不需要多个子类和父 Units 类。您可以简单地创建名为 WolfMonster、GoblinMonster 的不同怪物对​​象。

public class Monster {
    int health;
    int damage;
    int defense;
    String name;

    Monster(String name, int health, int damage, int defense)
    {
        this.name = name;
        this.health = health;
        this.damage = damage;
        this.defense = defense;
    }
    public boolean isAlive()
    {
        if(health >= 1){
            return true;
        }else{
            return false;
        }
    }    
}

public class FightManager {

    GameManager manage = new GameManager();
    Player player = new Player("Player",100,10,5);

    //changes

    Monster gobli = new Monster("Goblin", 40, 7, 4);
    Monster wolf = new Monster("Wolf",50,9,6);

    boolean myTurn = true;

    // To-Do
}

关于Java调用构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43852316/

相关文章:

java - 以编程方式添加 JPA EntityListener/Spring Data AuditingEntityListener

java - 从 PDFBox 1.x 迁移到 PDFBox 2

java - 是否可以实现由给定的 HashSet 实现支持的 MyHashMap?

java - 为什么还可以使用空白构造函数?

c++ - 为什么 C++ 不使用父类构造函数?

javascript - 如何从父对象构造函数访问对象

sql-server-2008 - 如何在sql server 2008中创建和调用标量函数

java - JAVA用户认证和登录系统

php - 使用 PHP 调用 SOAP API

javascript - jQuery Ajax 调用函数