java7 OOP一个英雄对应一把兵器 2022-02-05

public class Test1 {
    public static void main(String[] args) {
        Hero hero = new Hero("刘备", 300);
        Weapon weapon = new Weapon("双股剑", 3);
        //把两个对相关连起来
        hero.setWeapon(weapon);
        weapon.setHero(hero);
        //通过英雄获取他的信息
        String name=hero.getName();
        int age=hero.getAge();
        Weapon w=hero.getWeapon();
        System.out.println("我是"+name+"我"+age+"岁,我的武器是"+w.getName()
        +"武器等级是"+w.getGrade()+"级!");
    }
}
//英雄类
class Hero{
    private String name;//private修饰属性就是封装,封装后属性调用用getter setter方法
    private int age;
    private Weapon weapon;//一对一关系(一个英雄对应一把武器)
    public Weapon getWeapon() {
        return weapon;
    }
    public void setWeapon(Weapon weapon) {
        this.weapon = weapon;
    }
    public Hero(){}
    public Hero(String name, int age) {
        this.name = name;
        this.age = age;
    }
    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;
    }
}
//武器类
class Weapon{
    private String name;
    private int grade;
    private Hero hero;//一对一关系(一把武器对应一个英雄)
    public Hero getHero() {
        return hero;
    }
    public void setHero(Hero hero) {
        this.hero = hero;
    }
    public Weapon() {}
    public Weapon(String name, int grade) {
        this.name = name;
        this.grade = grade;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getGrade() {
        return grade;
    }
    public void setGrade(int grade) {
        this.grade = grade;
    }
}

你可能感兴趣的:(java7 OOP一个英雄对应一把兵器 2022-02-05)