问题:有一个老接口,现在需要添加一个新方法,又不想影响原来的实现
1. 使用接口的默认方法,可以写方法体,子类也可以重写,不需要的子类无感知。
public interface TestInterface {
void test1();
default void test2(){
System.out.println("默认方法");
}
static void test3(){
System.out.println("静态方法");
}
}
public abstract class TestAbstract implements TestInterface {
public void testNew(){
System.out.println("抽象方法");
}
}
public class TestServiceImpl extends TestAbstract implements TestInterface {
@Override
public void test1() {
System.out.println("接口方法");
}
public void test2(){
System.out.println("重写默认方法");
}
public void testNew(){
System.out.println("重写抽象类方法");
}
public static void main(String[] args) {
TestServiceImpl testService = new TestServiceImpl();
testService.test1();
testService.test2();
TestInterface.test3();
testService.testNew();
}
}
//执行结果
接口方法
重写默认方法
静态方法
重写抽象类方法
Process finished with exit code 0
2. 接口静态方法,直接使用接口调用。是接口的公共方法,不可被重写
注意:以上两种jdk8以上才支持
3. 定义抽象类,把新方法定义在抽象类里