您的位置:首页 > 其它

关于接口的一些思考

2015-04-17 09:13 295 查看
下面示例是模拟游戏《愤怒的小鸟》的实现。

//叫的方式的接口

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动作。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: