[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技术的标准严格学习文档,仅作参考交流使用,对于使用本文档的后果,作者不作任何口头或书面的承诺)