JAVA单排日记-2019/11/4

类作为成员变量类型

定义一个武器类

public class weapon {
    private String weaponName;

    public weapon() {
    }

    public weapon(String weaponName) {
        this.weaponName = weaponName;
    }

    public String getWeaponName() {
        return weaponName;
    }

    public void setWeaponName(String weaponName) {
        this.weaponName = weaponName;
    }
}

定义一个英雄类,其中用武器类作为成员变量的类型

public class Hero {
    private String name;
    private int age;
    private weapon wea;

    public Hero() {
    }

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

    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 getWea() {
        return wea;
    }

    public void setWea(weapon wea) {
        this.wea = wea;
    }
}

使用

public class Game{
    public static void main(String[] args) {
        Hero one = new Hero();
        one.setAge(13);
        one.setName("吕布");

        weapon wea1 = new weapon("方天画戟");
        one.setWea(wea1);
    }
}

接口作为成员变量类型

定义接口

public interface Skill {
    void skill();
}

定义英雄,使用接口作为成员变量类型

public class Hero {
    private String name;
    private int age;
    private weapon wea;
    private Skill skill;

    public Hero() {
    }

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

    public Skill getSkill() {
        return skill;
    }

    public void setSkill(Skill skill) {
        this.skill = skill;
    }

    public Hero(Skill skill) {
        this.skill = skill;
    }

    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 getWea() {
        return wea;
    }

    public void setWea(weapon wea) {
        this.wea = wea;
    }
}

使用

public class Game{
    public static void main(String[] args) {
        Hero one = new Hero();
        one.setAge(13);
        one.setName("吕布");

        weapon wea1 = new weapon("方天画戟");
        one.setWea(wea1);
创建匿名内部类
        Skill ski = new Skill() {  
            @Override
            public void skill() {
                System.out.println("释放技能");
            }
        };
        one.setSkill(ski);
    }
}

类作为方法的参数或返回值类型

在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值