JDK8以前,interface中能够定义常量和抽象方法,访问修饰符是public。java
public interface A { /** a1和a2写法是等价的 */ public static final int a1 = 0; int a2 = 0; /** methodA1和methodA2写法是等价的 */ public abstract void methodA1(); void methodA2(); }
JDK8起,容许咱们在interface中使用static和default修饰方法(使用这两种修饰符中其一就不能使用abstract修饰符),从而方法具备方法体。ide
public interface A { /** default访问修饰符修饰的方法 */ default void methodB1() { System.out.println("this is default method"); } /** static修饰符修饰的方法 */ public static void methodB2() { System.out.println("this is static method"); } }
default修饰的方法,经过接口的实现类的对象调用;static修饰的方法,直接经过接口名调用。this
public class Test implements A{ public static void main(String[] args) { /** 接口的default方法,经过接口的实现类的对象调用 */ Test test = new Test(); test.methodB1(); /** 接口的静态方法,经过接口名调用 */ A.methodB2(); } }
因为java支持一个实现类能够实现多个接口,若是多个接口中存在一样的static和default方法会怎么样呢?spa
public interface A { /** default访问修饰符修饰的方法 */ default void methodB1() { System.out.println("this is default method -- InterfaceA"); } /** static修饰符修饰的方法 */ public static void methodB2() { System.out.println("this is static method -- InterfaceA"); } } public interface B{ /** default访问修饰符修饰的方法 */ default void methodB1() { System.out.println("this is default method -- InterfaceB"); } /** static修饰符修饰的方法 */ public static void methodB2() { System.out.println("this is static method -- InterfaceB"); } } public class Test implements A,B{ /** 因为A和B中default方法同样,因此这里必须覆盖 */ @Override public void methodB1() { System.out.println("this is Overriding methods"); } public static void main(String[] args) { /** 接口的default方法,经过接口的实现类的对象调用 */ Test test = new Test(); test.methodB1(); /** A接口的静态方法,经过接口名调用 */ A.methodB2(); /** B接口的静态方法,经过接口名调用 */ B.methodB2(); } }
运行结果:.net
参考: https://blog.csdn.net/aitangyong/article/details/54134385code