亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在沒有靜態的情況下訪問不同類中的字段?(JAVA)

如何在沒有靜態的情況下訪問不同類中的字段?(JAVA)

慕哥9229398 2023-12-13 14:59:18
我正在創建一個戰斗模擬游戲。我有一個攻擊職業和一個戰士職業。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?}我如何才能訪問攻擊字段?謝謝。
查看完整描述

1 回答

?
夢里花落0921

TA貢獻1772條經驗 獲得超6個贊

正如您可以訪問類的實例方法一樣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;

    }

}


查看完整回答
反對 回復 2023-12-13
  • 1 回答
  • 0 關注
  • 157 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號