[BIT0429]-Java 接口(interface)详解一

来源:互联网 发布:帝国 织梦 编辑:程序博客网 时间:2024/06/03 16:04

[BIT0429]-Java 接口(interface)详解一
假设有三个类,分别是SuperMan、Plane和Bat,三者都有一个行为“飞”,此时就需要引入一个概念“接口(Interface)”来表示“飞这个行为”。
首先我们定义一个接口,在接口里面定义表示“飞”的这个方法:

public interface InterfaceFly {    public abstract void fly();}

然后分别定义三个类实现上述接口的方法:

package cn.bjsxt.oop01;public class Bat implements InterfaceFly{    @Override    public void fly() {        // TODO Auto-generated method stub        System.out.println("蝙蝠在夜里飞");    }}
package cn.bjsxt.oop01;public class Plane implements InterfaceFly {    @Override    public void fly() {        // TODO Auto-generated method stub        System.out.println("飞机在对流层飞");    }}
package cn.bjsxt.oop01;public class SuperMan implements InterfaceFly{    @Override    public void fly() {        // TODO Auto-generated method stub        System.out.println("超人在太空飞");    }}

最后在测试类里面运行程序,观察结果:

package cn.bjsxt.oop01;public class Test {    public static void main(String[] args) {        // TODO Auto-generated method stub        Bat bat=new Bat();        Plane plane=new Plane();        SuperMan superMan=new SuperMan();        showFly(bat);        showFly(plane);        showFly(superMan);    }    public static void showFly(Bat bat){        bat.fly();    }    public static void showFly(Plane plane){        plane.fly();    }    public static void showFly(SuperMan superMan){        superMan.fly();    }}

以下是运行结果:
这是本程序的运行结果

2017/10/24 BIT创作,您可以免费转载和使用!(本模块博客是作者学习期间整理的学习心得,不是java技术的标准严格学习文档,仅作参考交流使用,对于使用本文档的后果,作者不作任何口头或书面的承诺)

原创粉丝点击