自定义类作为数据类型

自定义类作为数据类型_第1张图片
Hero类

package role;

public class Hero {
    private String name;
    private int grade;
    private Weapon weapon;

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

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

    public Weapon getWeapon() {
        return weapon;
    }

    public void setWeapon(Weapon weapon) {
        this.weapon = weapon;
    }
    void attack(){
        System.out.println(grade+"级的"+name+"使用"+weapon.getCode()+"发动了攻击");
    }
}

Weapon类;

package role;

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

}

自定义类作为数据类型_第2张图片

运行

package role;

public class RunMain {
    public static void main(String[] args) {
        Weapon wuqi = new Weapon("大保剑");
        Hero obj = new Hero(wuqi,"盖伦",18);
        obj.setWeapon(wuqi);
        //使用英雄的攻击方法
        obj.attack();
    }
}

自定义类作为数据类型_第3张图片

你可能感兴趣的:(JAVA语法与面向对象)