在jdk8的时候,接口中可以定义静态方法static和默认方法default。
1. 静态方法(static方法)
public interface TestService {static void hello() {System.out.printf("hello");}static Long returnHello() {System.out.printf("returnHello");return 1L;}}
静态方法用static进行修饰,但是需要注意的是:
**static**方法不能被继承,也不能被重写。但是静态变量会被继承**static**方法不能被实现类调用,只能被自身调用。-
2. 默认方法(default方法)
public interface TestService {default void helloDefaule() {System.out.println("helloDefaule");}default Long helloDefaultReturn() {return returnHello();}static Long returnHello() {System.out.printf("returnHello");return 1L;}// 多个接口中都有defaultMethod,可以指定重写为哪个接口的 defaultMethod@Overridepublic void defaultMethod() {// TODO Auto-generated method stubDefalutTest.super.defaultMethod();}}
需要注意的是:
default方法可以被子接口继承亦可被其实现类所调用default方法被继承时,可以被子接口覆写- 如果一个类实现了多个接口,且这些接口中无继承关系,这些接口中若有相同的(同名,同参数)的
default方法,则接口实现类会报错,接口实现类必须通过特殊语法指定该实现类要实现那个接口的default方法(<接口>.super.<方法名>([参数]))
