简介
Before Java 8, interfaces could have only abstract methods. The implementation of these methods has to be provided in a separate class. So, if a new method is to be added in an interface, then its implementation code has to be provided in the class implementing the same interface. To overcome this issue, Java 8 has introduced the concept of default methods which allow the interfaces to have methods with implementation without affecting the classes that implement the interface.
(译文)Java8之前接口里的方法只能是抽象的,必须要在另一个类中实现这些方法。所以如果接口中添加了一个方法,那么在实现了该接口的类中也必须实现新添加的方法。为了克服这一问题,Java8引入了默认方法的概念,其允许接口中可以存在由方法体的方法,这样就不会影响到之前已实现该接口的类。
语法
1 | public interface InterfaceName { |
静态方法
Java8的另一个特性是接口可以声明(并且可以提供实现)静态方法。例如:
1 | public interface InterfaceName { |
默认方法和静态方法示例
1 | interface TestInterface1 { |
输出:
1 | Default TestInterface1 |
tips:
Q: 如何在静态方法中调用非静态方法?
A: 在静态方法中调用非静态方法的唯一解决办法为实例化含有非静态方法的类,然后用该类的实例化对象去调用非静态方法。因为根据定义可知,非静态方法由类的实例化对象调用,而静态方法本身就属于类!
更多详细内容参见官方文档