在之前的版本中,接口中的方法只能是抽象的,没有方法体的。但是Java8环境下可以定义的static静态方法,和default修饰的方法,都是可以带方法体的。
通过接口名调用静态方法,不能用实现类的实例调用(编译不通过)
public interface TestInterface {
static String testStatic() {
return "接口静态方法";
}
default String testDefault() {
return "接口默认方法";
}
}
public class TestInterfaceClass implements TestInterface{
public static void main(String[] args) {
TestInterfaceClass test = new TestInterfaceClass();
//输出“接口默认方法”
System.out.println(test.testDefault());
//输出“接口静态方法”
System.out.println(TestInterface.testStatic());
}
}
接口中的default方法只能用实现类的实例调用。
- 实现类只实现一个接口或者实现的多个接口中的default方法名不一样时,可以不重写接口中的default方法。
- 当实现的多个接口中有同名的default方法时,则必须重写同名的default方法。
public interface TestInterfaceCopy {
static String testStatic() {
return "接口静态方法----copy";
}
default String testDefault() {
return "接口默认方法----copy";
}
}
public class TestInterfaceClass implements TestInterface,TestInterfaceCopy{
public static void main(String[] args) {
TestInterfaceClass test = new TestInterfaceClass();
// 输出“接口默认方法----copy”
System.out.println(test.testDefault());
// 输出“接口静态方法”
System.out.println(TestInterface.testStatic());
// 输出“接口静态方法----copy”
System.out.println(TestInterfaceCopy.testStatic());
}
@Override
public String testDefault() {
// 重写了接口中重名的default方法,这里调用copy中的default方法,也可以自定义
return TestInterfaceCopy.super.testDefault();
}
}