其他分享
首页 > 其他分享> > 接口作为成员变量类型和接口作为方法的参数和或返回值

接口作为成员变量类型和接口作为方法的参数和或返回值

作者:互联网

public class Hero{
    private String name;//英雄的名称
    private Skill skill;//释放技能

    public Hero() {
    }

    @Override
    public String toString() {
        return "Hero{" +
                "name='" + name + '\'' +
                ", 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 Hero(String name, Skill skill) {
        this.name = name;
        this.skill = skill;
    }

    public void attack(){
        System.out.println("我叫" + name + ",开始释放技能");
        skill.use();
        System.out.println("技能释放完成");
    }
}


public interface Skill {
    void use();//释放技能的抽象方法
}

public class SkillImpl implements Skill{
    @Override
    public void use() {
        System.out.println("biu-biu-biu");
    }
}


public class MyTest {
    public static void main(String[] args) {
        Hero hero = new Hero();

        //设置英雄的名称
        hero.setName("艾希");

        //设置英雄技能
        hero.setSkill(new SkillImpl());
        hero.attack();
    }
}

接口作为方法的参数和或返回值

public class MyTest {
    public static void main(String[] args) {
        //左边是接口名称,右边是实现类名称,这就是多态写法
        List<String> list = new ArrayList<>();

        List<String> strings = addNames(list);
        strings.forEach(s -> System.out.println(s));
    }

    public static List<String> addNames(List<String> list){
        list.add("张三");
        list.add("李四");
        list.add("王五");

        return list;
    }
}

标签:name,list,void,作为,接口,返回值,skill,public,String
来源: https://www.cnblogs.com/ailhy/p/16441794.html