09 接口¶
本章目标¶
- 理解接口:定义"能做什么"的规范
- 掌握接口定义、实现、多接口
- 掌握默认方法与静态方法
- 理解接口 vs 抽象类的区别
9.1 什么是接口?¶
接口(interface) 定义一组"能力规范":规定实现它的类必须有哪些方法,但不管怎么实现。
接口:可攻击(Attackable)
└── 方法:attack(目标)
实现者:
└── 玩家类(能攻击)
└── 怪物类(能攻击)
└── 炮塔类(能攻击)
public interface Attackable {
void attack(Entity target); // 抽象方法:没有方法体
}
实现接口用 implements:
public class Zombie implements Attackable {
@Override
public void attack(Entity target) {
System.out.println("僵尸咬了一口 " + target.getName());
}
}
public class Turret implements Attackable {
@Override
public void attack(Entity target) {
System.out.println("炮塔发射炮弹打 " + target.getName());
}
}
9.2 面向接口编程¶
统一用接口类型操作不同的实现:
Attackable a1 = new Zombie();
Attackable a2 = new Turret();
a1.attack(target); // 僵尸咬
a2.attack(target); // 炮塔射
好处:新增实现不用改调用代码。比如加一个"弓箭手",只要实现 Attackable,老代码全部能用。
static void combat(Attackable attacker, Entity target) {
attacker.attack(target);
}
9.3 一个类可以实现多个接口¶
Java 类只能继承一个父类,但可以实现多个接口:
public interface Flyable {
void fly();
}
public interface Attackable {
void attack(Entity target);
}
public class Dragon implements Flyable, Attackable {
@Override
public void fly() { System.out.println("巨龙起飞"); }
@Override
public void attack(Entity target) { System.out.println("巨龙喷火"); }
}
为什么需要接口
Java 单继承限制了类只能有一个父类,但现实中的能力是多种组合的(会飞又会攻击、会游泳又会跑)。接口就是为"多能力组合"而生的。
9.4 接口的默认方法与静态方法(Java 8+)¶
默认方法(default)¶
给接口方法一个默认实现,实现类可以不重写:
public interface Damageable {
void takeDamage(int amount);
default boolean isDead(int hp) { // 默认方法
return hp <= 0;
}
}
好处:给接口加新方法时,不用改所有实现类(否则老实现类全部编译报错)。
静态方法¶
public interface ItemHelper {
static boolean isTool(String id) {
return id.endsWith("_sword") || id.endsWith("_pickaxe");
}
}
// 调用
ItemHelper.isTool("ffs_steel_sword"); // true
9.5 接口常量¶
接口里的变量自动是 public static final(常量):
public interface GameConstants {
int MAX_PLAYERS = 100; // 相当于 public static final int
double GRAVITY = 9.8;
}
9.6 接口 vs 抽象类¶
| 抽象类 | 接口 | |
|---|---|---|
| 关键字 | abstract class | interface |
| 继承数量 | 只能单继承 | 可多实现 |
| 构造器 | 有 | 没有 |
| 字段 | 可以任意 | 只能是常量 |
| 抽象方法 | 可以有 | 可以有 |
| 具体方法 | 可以有 | default/static |
| 语义 | "是什么"(is-a) | "能做什么"(can-do) |
经验法则: - 多个类有共同状态和行为(比如都有名字、血量)→ 用抽象类 - 多个类只有共同能力(都能攻击、都能被点燃)→ 用接口
9.7 实战:模组场景¶
Forge/NeoForge 里接口无处不在,比如:
// 简化版:让方块可被自定义工具挖掘
public interface CustomMineable {
boolean canHarvest(int toolLevel);
int getHardness();
}
// 实现:特殊矿石方块
public class MagicOreBlock implements CustomMineable {
@Override
public boolean canHarvest(int toolLevel) {
return toolLevel >= 3; // 需要 3 级工具
}
@Override
public int getHardness() {
return 15;
}
}
// 检查某个方块是否实现接口(配合 instanceof)
if (block instanceof CustomMineable mineable) {
if (mineable.canHarvest(playerToolLevel)) {
// 可以挖掘
}
}
9.8 小练习¶
- 定义接口
Soundable(方法 makeSound()),让 Dog 和 Cat 实现它 - 定义
Swimmable接口,让 Duck 同时实现 Soundable 和 Swimmable - 接口加一个 default 方法
describe(),返回"我会发声",在子类调用
本章小结¶
- 接口定义能力规范,implements 实现
- 一个类可实现多个接口(弥补单继承)
- default 方法给默认实现,static 方法直接调用
- 抽象类侧重"是什么",接口侧重"能做什么"
下一章:10 常用类与 API