接口(interface)是Java中的一种抽象类型,是比抽象类更抽象的存在,更专业的实现了规范和实现的分离。
声明格式
接口的访问修饰符可以是public或者默认(default),不能是private或protected
接口中的成员变量默认是public static final的常量,必须初始化
接口中的方法默认是public abstract的抽象方法,不能有方法体,必须由实现类来实现
接口可以继承多个接口,使用逗号分隔接口名
类实现接口使用implements关键字,类可以实现多个接口,使用逗号分隔接口名
实现类必须实现接口中的所有抽象方法,否则必须声明为抽象类
jdk8以后,接口可以包含默认方法(default method)和静态方法(static method),默认方法有方法体,静态方法也有方法体,可以直接通过接口名调用
1 2 3 4 5 6 [访问修饰符] interface 接口名 { }
代码示例 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 package study.ghr.pk1;interface Volant { int MAX_HEIGHT = 10000 ; public static void staticMethod () { System.out.println("Volant static method" ); } default void say () { System.out.println("Volant can say" ); } void fly () ; } interface Honest { void helpOther () ; } interface ISuperMan extends Volant , Honest { void saveTheWorld () ; } class Bird implements Volant { @Override public void fly () { System.out.println("Brid can fly" ); } } class BirdMan implements Volant , Honest { @Override public void fly () { System.out.println("BirdMan can fly" ); } @Override public void helpOther () { System.out.println("BirdMan can help other" ); } } class SuperMan implements ISuperMan { @Override public void fly () { System.out.println("SuperMan can fly" ); } @Override public void helpOther () { System.out.println("SuperMan can help other" ); } @Override public void saveTheWorld () { System.out.println("SuperMan can save the world" ); } } public class TestInterface { public static void main (String[] args) { System.out.println("Volant.MAX_HEIGHT = " + Volant.MAX_HEIGHT); Volant.staticMethod(); Bird b = new Bird (); b.fly(); BirdMan bm = new BirdMan (); bm.fly(); bm.helpOther(); SuperMan sm = new SuperMan (); sm.fly(); sm.helpOther(); sm.saveTheWorld(); sm.say(); Volant v = new SuperMan (); v.fly(); } }