6.9类作为成员变量类型

2019-03-28  本文已影响0人  十六只猴子王
package memberVariable;
//游戏当中的英雄角色类
public class Hero {
    private String name;
    private int age;
    private Weapon weapon;

   public Hero(String name, int age, Weapon weapon) {
        this.name = name;
        this.age = age;
        this.weapon = weapon;
    }

   public Hero() {
    }

   public String getName() {
        return name;
    }

   public void setName(String name) {
        this.name = name;
    }

   public int getAge() {
        return age;
    }

   public void setAge(int age) {
        this.age = age;
    }

   public Weapon getWeapon() {
        return weapon;
    }

   public void setWeapon(Weapon weapon) {
        this.weapon = weapon;
    }
   public void attack(){
        System.out.println("年龄为"+age+"的"+name+" 用"+weapon.getCode()+"攻击敌方");
    }
}
package memberVariable;

public class Weapon {
    private String code;//武器代号

    public Weapon(String code) {
        this.code = code;
    }

    public Weapon() {
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }
}
package memberVariable;

public class HeroMain {
    public static void main(String[] args) {
    //创建一个英雄角色
        Hero hero = new Hero();
        hero.setAge(20);
        hero.setName("阿丽塔");

        //创建一个武器对象
        Weapon weapon= new Weapon("腿");
        hero.setWeapon(weapon);
    }
}
上一篇下一篇

猜你喜欢

热点阅读