首先,从 Java 8 开始,接口可以包含默认方法,使用 default
关键字:
public interface InterfaceA {
default void method1() {
System.out.println("method1 from InterfaceA.");
}
default void method2() {
System.out.println("method2 from InterfaceA.");
}
void method3();
default void method4() {
System.out.println("method4 from InterfaceA.");
}
void method5();
default void method6() {
System.out.println("method6 from InterfaceA.");
}
}
public interface InterfaceB {
default void method1() {
System.out.println("method1 from InterfaceB.");
}
default void method2() {
System.out.println("method2 from InterfaceB.");
}
void method3();
void method4();
default void method5() {
System.out.println("method5 from InterfaceB.");
}
default void method7() {
System.out.println("method7 from InterfaceB.");
}
}
接着,接口类 TestService
多继承 InterfaceA
和 InterfaceB
:
public interface TestService extends InterfaceA, InterfaceB {
@Override
default void method1() {
InterfaceA.super.method1();
}
@Override
default void method2() {
InterfaceB.super.method2();
}
@Override
default void method4() {
InterfaceA.super.method4();
}
@Override
void method5();
}
method3
不用重写,是因为两个父接口均没有默认实现。method6
和method7
不用重写,是因为两个父接口没有产生冲突。- 其余方法都需要
TestService
重写。
最后,实体类 MyClass
实现 TestService
:
public static class MyClass implements TestService {
@Override
public void method3() {
}
@Override
public void method5() {
}
}
method1
、method2
和method4
不用重写,因为TestService
重写了这些方法,并添加了默认实现。method3
需要重写,因为所有父接口均没有实现。method5
需要重写,因为TestService
重写了此方法,但没有具体实现。method6
和method7
不用重写,因为TestService
没有重写这些方法,继承了父接口的默认实现。
测试
实际效果,可以通过以下代码进行测试:
public static void main(String[] args) {
TestService myClass = new MyClass();
myClass.method1();
myClass.method2();
myClass.method3();
myClass.method4();
myClass.method5();
myClass.method6();
myClass.method7();
}