类作为成员变量类型

Hero类

public class Hero {
    private String name;
    private int age;
    private Weapon weapon;//类作为成员变量类型

    public Hero() {
    }

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

    public void attack(){
        System.out.println("年龄为"+age+"的"+name+"用"+weapon.getCode()+"攻击敌人");//这里的武器需要用 对象.getCode()
    }

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

Weapon类

public class Weapon {
    private String code;

    public Weapon() {
    }

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

    public String getCode() {
        return code;
    }

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

main方法

public static void main(String[] args) {
        Hero hero = new Hero();
        hero.setName("Sherlock");
        hero.setAge(23);
        Weapon weapon = new Weapon("巴雷特");
        hero.setWeapon(weapon);
        hero.attack();//年龄为23的Sherlock用巴雷特攻击敌人
    }
上一篇:基于STM32F429使用RT-Thread实现web服务器功能


下一篇:Y1D001 什么是依赖注入