如何在没有静态的情况下访问其他类中的字段? (JAVA)

问题描述 投票:-1回答:2

我正在创建战斗模拟游戏。我有一个攻击类和一个战士类。


public class Attack {

    private String name;
    private int points;

    public Attack(String name, int points) {
        this.name= name;
        this.points =points;

    }

    //getters
    public String getName() {
        return name;
    }

    public int getPoints() {
        return points;
    }


    public String toString() {
        return ("Name of the attack = " + name + " damage = " + points) ;

    }

}

由于战士受到不同的攻击,因此我不能使用静态,因为它将覆盖先前的攻击。怪物类摘要:

        public Attack[] getAttacks() {
        return attacks;
    }
public void attack(String attackname, Warrior otherWarrior){
// How would I access the attack from the class?

}

我将如何访问“攻击”字段?谢谢。

java arrays static field
2个回答
0
投票

就像您可以访问this Monster类的实例方法一样,您可以访问Warrior类的实例方法:

public class Monster {
    Attack[] attacks;
    // ...

    public Attack[] getAttacks(){
        return attacks;
    }

    public void attack(String attackname, Warrior otherWarrior){
        Attack[] monsterAttacks = this.getAttacks();

        // Assuming Warrior has the method `getAttacks()`
        Attack[] warriorAttacks = otherWarrior.getAttacks();

        // ...
    }
}

public class Warrior {
    Attack[] attacks;
    // ...

    public Attack[] getAttacks() {
        return attacks;
    }
}

0
投票

为了访问攻击字段,您将需要使用下面的新运算符来创建Attack类的实例,

Attack attacker = new Attack();

attacker.getAttacks();

attacker.attack(attackName, otherWarrior);
© www.soinside.com 2019 - 2024. All rights reserved.