【Java专题】接口

接口(interface)是Java中的一种抽象类型,是比抽象类更抽象的存在,更专业的实现了规范和实现的分离。

声明格式

  • 接口的访问修饰符可以是public或者默认(default),不能是private或protected
  • 接口中的成员变量默认是public static final的常量,必须初始化
  • 接口中的方法默认是public abstract的抽象方法,不能有方法体,必须由实现类来实现
  • 接口可以继承多个接口,使用逗号分隔接口名
  • 类实现接口使用implements关键字,类可以实现多个接口,使用逗号分隔接口名
  • 实现类必须实现接口中的所有抽象方法,否则必须声明为抽象类
  • jdk8以后,接口可以包含默认方法(default method)和静态方法(static method),默认方法有方法体,静态方法也有方法体,可以直接通过接口名调用
1
2
3
4
5
6
[访问修饰符] interface 接口名 {
// 常量
// 抽象方法
// 默认方法(default method 可选)
// 静态方法(static method 可选)
}

代码示例

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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package study.ghr.pk1;

interface Volant {
int MAX_HEIGHT = 10000; // 相当于 public static final int MAX_HEIGHT = 10000;

// 新增的静态方法
public static void staticMethod() {
System.out.println("Volant static method");
}

// 新增的默认方法,子类可以直接使用或者重写
default void say() {
System.out.println("Volant can say");
}
void fly(); // 相当于 public abstract void fly();
}

interface Honest {
void helpOther();
}

// 接口可以继承多个接口
interface ISuperMan extends Volant, Honest {
void saveTheWorld();
}

// 类使用 implements 实现接口
class Bird implements Volant {
@Override
public void fly() {
System.out.println("Brid can fly");
}
}

// 类可以实现多个接口
class BirdMan implements Volant, Honest {
@Override
public void fly() {
System.out.println("BirdMan can fly");
}

@Override
public void helpOther() {
System.out.println("BirdMan can help other");
}
}

class SuperMan implements ISuperMan {
@Override
public void fly() {
System.out.println("SuperMan can fly");
}

@Override
public void helpOther() {
System.out.println("SuperMan can help other");
}

@Override
public void saveTheWorld() {
System.out.println("SuperMan can save the world");
}
}

public class TestInterface {
public static void main(String[] args) {
System.out.println("Volant.MAX_HEIGHT = " + Volant.MAX_HEIGHT); // 10000
// Volant.MAX_HEIGHT = 20000; // 编译错误,接口中的常量不能修改

Volant.staticMethod(); // Volant static method

Bird b = new Bird();
b.fly(); // Brid can fly

BirdMan bm = new BirdMan();
bm.fly(); // BirdMan can fly
bm.helpOther(); // BirdMan can help other

SuperMan sm = new SuperMan();
sm.fly(); // SuperMan can fly
sm.helpOther(); // SuperMan can help other
sm.saveTheWorld(); // SuperMan can save the world
sm.say(); // SuperMan can say 接口中的默认方法可以被子类继承和调用

Volant v = new SuperMan(); // 父类对象指向子类引用,向上转型,自动转型
v.fly(); // SuperMan can fly 运行时根据对象的实际类型调用方法
}
}