其他分享
首页 > 其他分享> > 类做位成员变量类型和接口作为成员变量类型

类做位成员变量类型和接口作为成员变量类型

作者:互联网

类做位成员变量类型

英雄类

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

    public Hero() {
    }
    public void  att(){
        System.out.println("年龄为:"+age+"的"+name+"用"+weapon.getCode()+"攻击野猪");
    }

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

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

武器类

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

测试类

public class test {
    public static void main(String[] args) {
        Hero hero = new Hero();
        hero.setName("伊丽莎白");
        hero.setAge(18);

        Weapon weapon = new Weapon("多兰剑");
        hero.setWeapon(weapon);

        hero.att();
    }
}

 

接口作为成员变量类型

英雄类

public class Hero {
    private String name;
    private Skill skill;

    public Hero() {
    }

    public void arr(){
        System.out.println("我叫"+name+",开始释放技能:");
        skill.use();
        System.out.println("技能释放完成");
    }
    public Hero(String name, Skill skill) {
        this.name = name;
        this.skill = skill;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Skill getSkill() {
        return skill;
    }

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

释放技能的接口

public interface Skill {
    void use();
}

释放技能的接口的实现类

public class SkillImpl implements Skill{
    @Override
    public void use() {
        System.out.println("龙卷风摧毁停车场");
    }
}

测试类

public class test {
    public static void main(String[] args) {
        Hero hero = new Hero();
        hero.setName("二哈");
        //hero.setSkill(new SkillImpl());
        //匿名内部类
//        Skill skill = new Skill(){
//            @Override
//            public void use() {
//                System.out.println("乌鸦坐飞机");
//            }
//        };
//        hero.setSkill(skill);
        hero.setSkill(new Skill() {
            @Override
            public void use() {
                System.out.println("老鹰捉小鸡");
            }
        });
        hero.arr();
    }
}

 

标签:做位,hero,String,成员,name,void,skill,public,变量
来源: https://www.cnblogs.com/yuzong/p/16444475.html