package neibulei.Demo7;
public interface Skill {
void use(); //释放技能的抽象方法
}
====================
package neibulei.Demo7;
public class SkillImple implements Skill{
@Override
public void use() {
System.out.println("11111");
}
}
===========
package neibulei.Demo7;
public class Hero {
private String name;
private Skill skill;
public Hero(String name, Skill skill) {
this.name = name;
this.skill = skill;
}
public Hero() {
}
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(name+" ");
**skill.use();** //调用抽象方法
System.out.println("完成");
}
}
================
package neibulei.Demo7;
public class DemoTest {
public static void main(String[] args) {
Hero hero=new Hero();
hero.setName("小炮");
hero.setSkill(new SkillImple()); //使用单独定义的实现类 发生了自动向上转型
hero.attack();
System.out.println("========");
Skill skill=new Skill() { //使用匿名内部类来实现
@Override
public void use() {
System.out.println("打炮");
}
};
hero.setSkill(skill);
hero.attack();
System.out.println("=======");
hero.setSkill(new Skill() { //使用匿名内部类的匿名对象
@Override
public void use() {
System.out.println("疯狂打炮");
}
});
hero.attack();
System.out.println("=======");
}
}