自定义类作为数据类型

在这里插入图片描述
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;
    }

}

在这里插入图片描述

运行

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

在这里插入图片描述

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值