其他分享
首页 > 其他分享> > 类作为成员变量类型

类作为成员变量类型

作者:互联网

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用巴雷特攻击敌人
    }

标签:变量,name,weapon,public,age,类型,Weapon,成员,String
来源: https://blog.csdn.net/SherlockWZX/article/details/118650590