接口中的default方法
现有接口MyInterface,有两个方法show1与show2
相当于规定实现这个接口类的对象必须有show1与show2这两个功能。
package InterfaceNew.DefaultDemo;
public interface MyInterface {
void show1();
void show2();
}
实现MyInterface的实现类:
package InterfaceNew.DefaultDemo;
public class MyInterfaceImplOne implements MyInterface{
@Override
public void show1() {
System.out.println("show1");
}
@Override
public void show2() {
System.out.println("show2");
}
}
但是如果我们想让实现这个接口的实现类额外添加一个功能的话,如果直接在MyInterface接口上添加一个
void show3();并不太好,因为这样会使得其他所有实现这个接口的实现类报错,因为他们没有对新增的这个方法show3重写。
所以这里可以对新增的方法使用default关键字修饰。 这样的话,MyInterfaceImplOne类就可以直接使用这个show3方法而不需要重写了。但是如果需要的话,也是可以对这个Default方法进行重写的。
default关键字
package InterfaceNew.DefaultDemo;
public interface MyInterface {
void show1();
void show2();
default void show3(){
System.out.println("show3");
}
}
并且还需注意,如果一个实现类同时实现两个接口,那么这两个接口不能有相同名称的Default方法,不然会报错的。
接口中的静态方法
接口静态方法只能通过接口调用,不能通过实现类调用。因为如果这个实现类实现了两个接口,并且这两个接口都有同一个静态方法test,那么编译器将不知道执行哪个test。
接口中的私有方法
接口Inter中定义默认方法与静态方法。使用私有方法将共性进行精简,这也是借口中私有方法的作用。(也就是共同存在的语句:打印1,2,3)
Inter
package InterfaceNew.PrivateDemo;
public interface Inter {
default void show1(){
System.out.println("show1开始");
method();
System.out.println("show1结束");
}
default void show2(){
System.out.println("show1开始");
method();
System.out.println("show1结束");
}
default void method1(){
System.out.println("method1开始");
method();
System.out.println("method1结束");
}
default void method2(){
System.out.println("method2开始");
method();
System.out.println("method2结束");
}
default void method(){
System.out.println("1");
System.out.println("2");
System.out.println("3");
}
}
InterDemo
package InterfaceNew.PrivateDemo;
public class InterDemo {
public static void main(String[] args) {
Inter ii=new InterImpl();
ii.show1();
ii.show2();
ii.method1();
ii.method2();
}
}
InterImpl
public class InterImpl implements Inter{
}
执行结果: