在 java 8 之前,接口與其實(shí)現(xiàn)類之間的 耦合度 太高了(tightly coupled),當(dāng)需要為一個(gè)接口添加方法時(shí),所有的實(shí)現(xiàn)類都必須隨之修改。默認(rèn)方法解決了這個(gè)問(wèn)題,它可以為接口添加新的方法,而不會(huì)破壞已有的接口的實(shí)現(xiàn)。接口默認(rèn)方法有兩種:
1. 非靜態(tài)默認(rèn)方法
- 定義
package com.test
public interface DefaultTest {
default void print() {
System.out.println("我是非靜態(tài)方法!");
}
}
- 使用
package com.test
public class DefaultTestImpl implements DefaultTest {
@Override
public void print() {
DefaultTest.super.print(); // 繼承父親的內(nèi)容
System.out.println("我是非靜態(tài)方法兒子!");
}
public static void main(String[] args) {
new DefaultTestImpl().print();
}
}
2. 靜態(tài)默認(rèn)方法
- 定義
package com.test
public interface StaticTest {
static void print() {
System.out.println("我是靜態(tài)方法!");
}
}
-
使用1
靜態(tài)方法不能重寫,只能使用。
package com.test
public class StaticTestImpl implements StaticTest {
public static void main(String[] args) {
StaticTest.print();
}
}
-
使用2
不在同一包下。
package com.another
import com.test.StaticTest;
public class StaticTestUser{
public static void main(String[] args) {
StaticTest.print();
}
}