【问题标题】:How to access a field in a different class without static? (JAVA)如何在没有静态的情况下访问不同类中的字段? (JAVA)
【发布时间】:2019-10-23 14:43:33
【问题描述】:

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


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

    }

}

由于战士的攻击方式不同,我不能使用静态,因为它会覆盖之前的攻击。 Monster类的片段:

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

}

我如何才能访问攻击字段? 谢谢。

【问题讨论】:

  • 我怎样才能访问攻击字段?您的字段有 getters,不是吗?只是用它来获得你的价值观。 attack.getName()
  • 你能发布你对战士类的定义吗?没有它,您的问题有点令人困惑。

标签: java arrays static field


【解决方案1】:

正如您可以访问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;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多