Java接口

每日一言

Being strong on your own is meaningless. To have power you need other people, and they need a world where they can be at their best. – Shiroe
from Log Horizon

Java 接口

Java编程语言中是一个抽象类型,是抽象方法的集合。

  • 接口中的所有方法默认是public abstract
  • 接口中的所有变量默认是 public static final 的常量
  • 接口不能被实例化,需要由类来实现
  • 一个类可以实现多个接口
  • 接口可以继承其他接口

接口的声明

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
[访问修饰符] interface <_name> [exdends <name>,<name>,...]{ //可以继承多个接口
// 声明变量
// 抽象方法
}

public interface InterfaceName {
// 常量定义
type CONSTANT_NAME = value;

// 抽象方法
returnType methodName(parameterList);

// Java 8 后可定义默认方法
default returnType methodName(parameterList) {
// 方法体
}

// Java 8 后可定义静态方法
static returnType methodName(parameterList) {
// 方法体
}

// Java 9 后可定义私有方法
private returnType methodName(parameterList) {
// 方法体
}
}

接口的实现

类可以实现接口:

1
2
3
4
5
6
7
public class ClassName implements InterfaceName {
// 必须实现接口中定义的所有抽象方法
@Override
public returnType methodName(parameterList) {
// 实现代码
}
}

类实现接口时,必须要实现接口中所有的抽象方法,默认方法可以不实现。否则必须要声明为抽象类

java中类可以一次实现多个接口。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class MyClass implements Interface1, Interface2, Interface3 {
// 必须实现所有接口中的方法

@Override
public void method1() {
// Interface1的方法实现
}

@Override
public void method2() {
// Interface2的方法实现
}

@Override
public void method3() {
// Interface3的方法实现
}
}

接口的继承

接口的继承与类相似,但是可以同时继承多个接口,而类一次只能继承一个父类。

1
public interface Hockey extends Sports, Event

Java接口
http://blog.ulna520.com/2025/03/28/Java接口_20250328_223942/
Veröffentlicht am
March 28, 2025
Urheberrechtshinweis