java8中为接口新增了一项功能:定义一个或者更多个静态方法。用法和普通的static方法同样。java
public interface InterfaceA { /** * 静态方法 */ static void showStatic() { System.out.println("InterfaceA++showStatic"); } }
测试ide
public class Test { public static void main(String[] args) { InterfaceA.show(); } }
结果测试
InterfaceA++showStatic
注意,实现接口的类或者子接口不会继承接口中的静态方法spa
在接口中,增长default方法, 是为了既有的成千上万的Java类库的类增长新的功能, 且没必要对这些类从新进行设计。 好比, 只需在Collection接口中
增长default Stream stream(), 相应的Set和List接口以及它们的子类都包含此的方法, 没必要为每一个子类都从新copy这个方法。设计
public interface InterfaceA { /** * 静态方法 */ static void showStatic() { System.out.println("InterfaceA++showStatic"); } /** * 默认方法 */ default void showDefault() { System.out.println("InterfaceA ++showDefault"); } } /**先只实现这个接口 */ public class InterfaceAImpl implements InterfaceA{ }
测试code
public class Test { public static void main(String[] args) { InterfaceA.showStatic(); new InterfaceAImpl().showDefault(); } }
结果继承
InterfaceA++showStatic InterfaceA ++showDefault
若是接口中的默认方法不能知足某个实现类须要,那么实现类能够覆盖默认方法。接口
public class InterfaceAImpl implements InterfaceA{ /** * 跟接口default方法一致,但不能再加default修饰符 */ @Override public void showDefault(){ System.out.println("InterfaceAImpl++ defaultShow"); } }
测试string
public class Test { public static void main(String[] args) { InterfaceA.showStatic(); new InterfaceAImpl().showDefault(); } }
结果it
InterfaceA++showStatic InterfaceAImpl++ defaultShow
新建立个接口InterfaceB
/** */ public interface InterfaceB { /** * 静态方法 */ static void showStatic() { System.out.println("InterfaceB++showStatic"); } /** * 默认方法 */ default void showDefault() { System.out.println("InterfaceB ++showDefault"); } }
若是不加剧写方法就会报错,由于实现类不知道你使用的是哪一个接口中的默认方法:
public class InterfaceAImpl implements InterfaceA,InterfaceB{
}
修改实现类
public class InterfaceAImpl implements InterfaceA,InterfaceB{ @Override public void showDefault() { System.out.println("InterfaceAImpl ++ showDefault"); }
测试结果
InterfaceA++showStatic InterfaceAImpl ++ showDefault
须要注意一点就是若是实现多个接口时,每一个接口都有相同的default方法须要重写该方法。