Java 8 Default And Static Methods In Interface

本文最后更新于 2024年4月15日 下午

Introduction

在 Java 8 之前接口的维护代价是高昂的,因为修改了接口的抽象方法,需要在所有的实现类都要重写该方法。

在 Java 8 中引入了接口中的默认方法(Default Methods)和静态方法(Static Methods)。

默认方法是接口中的一个新特性,它允许在接口中提供默认的方法实现,而不需要实现类去重写该方法。
默认方法使用 default 关键字来修饰方法,并且提供了默认的方法体实现。

静态方法是接口中的另一个新特性,它允许在接口中定义静态方法,这些方法可以直接通过接口名称调用,不需要实现类的实例。
静态方法使用 static 关键字来修饰方法。

Default Methods

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
public interface Vehicle {
// 默认方法
default void start() {
System.out.println("Vehicle is starting...");
}

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

// 实现接口
public class Car implements Vehicle {
// 实现抽象方法
@Override
public void stop() {
System.out.println("Car is stopping...");
}
}

// 测试
public class Main {
public static void main(String[] args) {
Car car = new Car();
car.start(); // 调用默认方法
car.stop(); // 调用实现方法
}
}

Static Methods

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public interface MathOperation {
// 静态方法
public static int add(int a, int b) {
return a + b;
}
}

// 测试
public class Main {
public static void main(String[] args) {
int result = MathOperation.add(5, 3); // 调用静态方法
System.out.println("Result: " + result);
}
}

Java 8 Default And Static Methods In Interface
https://stein283036.github.io/2024/04/15/Default-And-Static-Methods-In-Interface/
作者
倪京龙
发布于
2024年4月15日
更新于
2024年4月15日
许可协议