新特性04| 默认方法

简介

Before Java 8, interfaces could have only abstract methods. The implementation of these methods has to be provided in a separate class. So, if a new method is to be added in an interface, then its implementation code has to be provided in the class implementing the same interface. To overcome this issue, Java 8 has introduced the concept of default methods which allow the interfaces to have methods with implementation without affecting the classes that implement the interface.

(译文)Java8之前接口里的方法只能是抽象的,必须要在另一个类中实现这些方法。所以如果接口中添加了一个方法,那么在实现了该接口的类中也必须实现新添加的方法。为了克服这一问题,Java8引入了默认方法的概念,其允许接口中可以存在由方法体的方法,这样就不会影响到之前已实现该接口的类。

语法

1
2
3
4
5
public interface InterfaceName {
default return_type method_name(){
// default method body;
}
}

静态方法

Java8的另一个特性是接口可以声明(并且可以提供实现)静态方法。例如:

1
2
3
4
5
public interface InterfaceName {
static return_type method_name(){
// static method body;
}
}

默认方法和静态方法示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
interface TestInterface1 {
// 默认方法
default void printDefault() {
System.out.println("Default TestInterface1");
}

// 静态方法
static void printStatic() {
System.out.println("Static TestInterface1");
}
}

interface TestInterface2 {
// 默认方法
default void printDefault() {
System.out.println("Default TestInterface2");
}

// 静态方法
static void printStatic() {
System.out.println("Static TestInterface2");
}

// 抽象方法
void printAbstract();
}

// 实现类
public class Java8Test implements TestInterface1, TestInterface2 {
// 复写默认方法 printDefault()
public void printDefault() {
// 使用关键字super调用指定接口的默认方法
TestInterface1.super.printDefault();
TestInterface2.super.printDefault();
}

@Override
public void printAbstract() {
System.out.println("Abstract Java8Test");
}

public static void main(String[] args) {
Java8Test java8 = new Java8Test();

// 打印默认方法
java8.printDefault();

// 打印静态方法
TestInterface1.printStatic();
TestInterface2.printStatic();

// 打印已实现的抽象方法
java8.printAbstract();
}
}

输出:

1
2
3
4
5
Default TestInterface1
Default TestInterface2
Static TestInterface1
Static TestInterface2
Abstract Java8Test

tips:
Q: 如何在静态方法中调用非静态方法?
A: 在静态方法中调用非静态方法的唯一解决办法为实例化含有非静态方法的类,然后用该类的实例化对象去调用非静态方法因为根据定义可知,非静态方法由类的实例化对象调用,而静态方法本身就属于类!


更多详细内容参见官方文档

码哥 wechat
欢迎关注个人订阅号:「码上行动GO」