关于接口的一些思考

下面示例是模拟游戏《愤怒的小鸟》的实现。

//叫的方式的接口

public interface ShoutType {
public void shout();
}

//嗷嗷叫

public class AoShout implements ShoutType {
public void shout() {
System.out.println("嗷嗷叫");
}
}

//喳喳叫

public class ZhaShout implements ShoutType {
@Override
public void shout() {
System.out.println("喳喳叫");
}
}

//鸟的抽象类

public abstract class Bird {
ShoutType shout_type;//接口作为属性

public Bird(ShoutType shout_type) {
super();
this.shout_type = shout_type;
}
public void shout() {
shout_type.shout();// 调用接口的方法
}
public void fly() {
System.out.println("弹射飞");
}
public abstract void attact();
}

//炸弹鸟

public class BombBird extends Bird {
public BombBird(ShoutType shout_type) {
super(shout_type);
}
public void attact() {
System.out.println("炸弹攻击");
}
}

//分裂鸟

public class SplitBird extends Bird {
public SplitBird(ShoutType shout_type) {
super(shout_type);
}
public void attact() {
System.out.println("分裂攻击");
}
}

//测试类

public class BirdTest {
public static void main(String[] args) {
ShoutType ao_shout = new AoShout();
ShoutType zha_shout = new ZhaShout();


Bird bomb = new BombBird(zha_shout);
Bird split = new SplitBird(ao_shout);
bomb.shout();
split.shout();
}
}

这个示例是将接口的对象作为抽象类的一个属性,并且在构造方法中对其初始化,在各个子类中调用父类的构造方法,实现对叫的方式的初始化。

一种用法是定义一个方法,将接口作为参数传进来,方法体里面直接调用接口里的抽象方法。

另外一种用法是将实现接口的类以接口作为类型进行强制转换。(Interface)sub_class


定义接口:
interface Fight{
    void fight();


肥肥和瘦瘦去实现这个接口:
class FatFat implements Fight{
    public void fight(){

  System.out.println("FatFat 打人很痛!");
   }
}

class ThinThin implements Fight{
 public void fight(){
    System.out.println("ThinThin 打人一点都不痛!!哈哈。");

  }
}

然后你可能会这另一个类中使用到FatFat和ThinThin的对象,然后都去执行fight,但是你可能不到运行时就不会知道是具体的那个类的对象,这是你就感谢他们都实现了Fight接口,你可以向上转型,然后通过运行时的多态产生你想要的行为。

Fight a=new FatFat();
Fight b=new ThinThin();
a.fight();
b.fight();
这样就会执行不同的动作。

或者如果你有一个方法
f(Fight i){

  i.fight();
}

如果c是实现了Fight接口的其中一个类,那么你就可以这样使用这个方法:
f(c);
你不需要知道c究竟是什么对象(不管是FatFat还是ThinThin),你都可以得到你想要的fight动作。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值