day10-接口的默认方法的定义和使用
This commit is contained in:
@@ -0,0 +1,25 @@
|
||||
package com.inmind.interface_default02;
|
||||
/*
|
||||
JDK8时提供,接口的默认方法
|
||||
|
||||
接口的默认方法的使用步骤:
|
||||
1.接口不能创建对象的,它没有构造方法
|
||||
2.定义一个实现类,实现该接口,并实现接口中的所有的抽象方法
|
||||
public class MyInterfaceImpl(实现类) implements MyInterface(接口){
|
||||
3.创建该接口的实现类的对象,调用接口的抽象方法和默认方法
|
||||
4.在接口的实现类中,可以根据对应的需求,选择性重写,或不重写接口中的默认方法,也可以沿用功能(接口.super.默认方法名)(重点)
|
||||
*/
|
||||
public class Demo02 {
|
||||
public static void main(String[] args) {
|
||||
//创建接口的实现类的对象1
|
||||
MyInterfaceImpl1 myInterface1 = new MyInterfaceImpl1();
|
||||
myInterface1.method1();
|
||||
myInterface1.method2();
|
||||
myInterface1.method3();
|
||||
//创建接口的实现类的对象2
|
||||
MyInterfaceImpl2 myInterface2 = new MyInterfaceImpl2();
|
||||
myInterface2.method1();
|
||||
myInterface2.method2();
|
||||
myInterface2.method3();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.inmind.interface_default02;
|
||||
/*
|
||||
第一个版本的规则(接口),有一个固定功能method
|
||||
第二个版本中,需要增加功能
|
||||
|
||||
接口是可以升级的,添加新功能,之前添加功能只能通过抽象方法,导致所有的实现类都报错,这样非常麻烦。
|
||||
为了解决该问题,jdk8提供了默认方法来解决
|
||||
|
||||
接口中的默认方法的定义格式:
|
||||
public default 返回值类型 方法名(参数列表){
|
||||
默认实现
|
||||
}
|
||||
|
||||
*/
|
||||
public interface MyInterface {
|
||||
//十年之前的规范
|
||||
public abstract void method1();
|
||||
void method2();
|
||||
//十年之后增加新的规范了,就应该增加默认方法即可
|
||||
public default void method3(){
|
||||
System.out.println("接口中的新增的默认功能");
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.inmind.interface_default02;
|
||||
|
||||
public class MyInterfaceImpl1 implements MyInterface{
|
||||
@Override
|
||||
public void method1() {
|
||||
System.out.println("实现类1中method1方法");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void method2() {
|
||||
System.out.println("实现类1中method2方法");
|
||||
}
|
||||
|
||||
//ctrl+o
|
||||
|
||||
|
||||
@Override
|
||||
public void method3() {
|
||||
MyInterface.super.method3();//沿袭(沿用)接口中的默认功能
|
||||
//也可以选择性扩展增强
|
||||
System.out.println("实现类1扩展增强了method3");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.inmind.interface_default02;
|
||||
|
||||
public class MyInterfaceImpl2 implements MyInterface{
|
||||
@Override
|
||||
public void method1() {
|
||||
System.out.println("实现类2中method1方法");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void method2() {
|
||||
System.out.println("实现类2中method2方法");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void method3() {
|
||||
//直接重新实现method3的全部功能
|
||||
System.out.println("实现类2直接重新实现了method3的功能");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user