码迷,mamicode.com
首页 > 其他好文 > 详细

接口作为成员变量类型

时间:2020-03-04 19:31:35      阅读:109      评论:0      收藏:0      [点我收藏+]

标签:ring   size   tac   div   void   print   rgs   over   private   

package Yasuo;

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

    public Gay() {
    }

    public Gay(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 void attack() {
        System.out.println(getName() + "使用技能: ");
        skill.use();
        System.out.println("技能使用完毕");
    }
}
package Yasuo;

public interface Skill {
    void use();
}
package Yasuo;

public class SkillImpl implements Skill {

    @Override
    public void use() {
        System.out.println("斩钢闪");
    }
}
package Yasuo;

public class demo2main {
    public static void main(String[] args) {
        Gay gay = new Gay();
        gay.setName("亚索");
        Skill skill = new SkillImpl();  //或者直接 gay.setSkill(new SkillImpl);
        gay.setSkill(skill);
        gay.attack();

        System.out.println("=============");

        Skill skill2 = new Skill() {
            @Override
            public void use() {
                System.out.println("狂风绝息斩");
            }
        };
        gay.setSkill(skill2);
        gay.attack();

        System.out.println("============");

        gay.setSkill(new Skill() {
            @Override
            public void use() {
                System.out.println("踏前斩");
            }
        });
        gay.attack();
    }
}

 

接口作为成员变量类型

标签:ring   size   tac   div   void   print   rgs   over   private   

原文地址:https://www.cnblogs.com/aoligei/p/12411371.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!