静态嵌套类
定义静态嵌套类,将其作为关联的辅助类型,且不依赖外部类实例引用
静态嵌套类 是 CoddyKit 上的免费 Java Academy 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Java Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Java Academy 课程共包含 4 节课。
静态嵌套类
静态嵌套类是在另一个类内部使用 static 关键字定义的类。它不引用外部类实例,只是与外部类进行逻辑分组。
声明静态嵌套类
从外部访问嵌套类时,请使用外部类的名称。
class LinkedList<T> {
private Node<T> head;
// Static nested class — no outer instance reference
private static class Node<T> {
T data;
Node<T> next;
Node(T data) { this.data = data; }
}
public void addFirst(T item) {
Node<T> node = new Node<>(item);
node.next = head;
head = node;
}
}从外部访问
请使用 OuterClass.InnerClass 引用公共静态嵌套类。
class Builder {
public static class Config {
public final String host;
public final int port;
Config(String host, int port) {
this.host = host; this.port = port;
}
}
}
Builder.Config config = new Builder.Config("localhost", 8080);
System.out.println(config.host + ":" + config.port); // localhost:8080静态嵌套类与内部类
关键区别在于:静态嵌套类没有指向外部实例的隐式引用。Inner(非静态)类 DO 具有此类引用。
class Outer {
private int x = 10;
// Static nested: no access to x
static class StaticNested {
void doSomething() {
// System.out.println(x); // compile error — no outer reference!
System.out.println("Static nested");
}
}
// Inner class: has access to x
class Inner {
void doSomething() {
System.out.println(x); // 10 — can access outer fields
}
}
}使用静态嵌套类实现构建器模式
经典的构建器模式会使用静态嵌套类,因此调用方无需外部实例即可创建构建器。
class Pizza {
private final String size, crust;
private final List<String> toppings;
private Pizza(Builder b) {
this.size = b.size; this.crust = b.crust; this.toppings = List.copyOf(b.toppings);
}
public static class Builder {
private String size = "medium", crust = "thin";
private List<String> toppings = new ArrayList<>();
public Builder size(String s) { this.size = s; return this; }
public Builder crust(String c) { this.crust = c; return this; }
public Builder topping(String t) { this.toppings.add(t); return this; }
public Pizza build() { return new Pizza(this); }
}
}映射中的条目
Map.Entry 是一种广为人知的静态嵌套接口,用于遍历键值对。
import java.util.*;
Map<String, Integer> scores = Map.of("Alice", 95, "Bob", 87, "Carol", 92);
for (Map.Entry<String, Integer> entry : scores.entrySet()) {
System.out.printf("%-10s: %d%n", entry.getKey(), entry.getValue());
}
// Modern: using var
for (var entry : scores.entrySet()) {
System.out.println(entry.getKey() + " -> " + entry.getValue());
}使用静态嵌套类进行测试
在单元测试中,静态嵌套类可以保存测试夹具或模拟实现,并将其作用域限定在测试类内。
class UserServiceTest {
// Static nested fake/stub — no outer instance needed
static class FakeUserRepository implements UserRepository {
private final Map<Long, User> store = new HashMap<>();
public void save(User u) { store.put(u.id(), u); }
public Optional<User> findById(long id) {
return Optional.ofNullable(store.get(id));
}
}
// @Test methods use FakeUserRepository
void testFindUser() {
FakeUserRepository repo = new FakeUserRepository();
// ...
}
}使用静态嵌套类组织领域逻辑
在领域模型中,可以使用静态嵌套类将相关类型分组,以改善组织结构。
class Order {
private final long id;
private final List<LineItem> items;
// Static nested — logically belongs to Order, no outer reference needed
public static class LineItem {
public final String sku;
public final int quantity;
public final double unitPrice;
public LineItem(String sku, int qty, double price) {
this.sku = sku; this.quantity = qty; this.unitPrice = price;
}
public double total() { return quantity * unitPrice; }
}
// ...
}比较:静态嵌套类与顶层类
如果某个类只在外部类的上下文中使用,请优先选择静态嵌套类。如果该类具有更广泛的适用范围,请使用顶层类。
带泛型的静态嵌套类
静态嵌套类与顶层类一样可以参与泛型机制。
class Pair<A, B> {
// Static nested with its own type params
public static class Mutable<X, Y> {
public X first;
public Y second;
public Mutable(X first, Y second) {
this.first = first; this.second = second;
}
}
public static <X, Y> Mutable<X, Y> mutableOf(X x, Y y) {
return new Mutable<>(x, y);
}
}
Pair.Mutable<String, Integer> p = Pair.mutableOf("Alice", 30);
System.out.println(p.first + " is " + p.second); // Alice is 30内存效率
静态嵌套类不会持有对外部实例的引用。这样可以避免在内存中意外保留外部对象,从而防止长期存在的结构发生内存泄漏。
快速检查
静态嵌套类与内部(非静态)类的区别是什么?
回顾:静态嵌套类
要点:
- 静态嵌套类与外部类进行分组,但没有外部实例引用
- 从外部访问:OuterClass.NestedClass
- 没有隐式引用意味着不会意外保留外部实例,导致其无法释放
- 构建器模式通常使用静态嵌套的 Builder 类
- Map.Entry 是广为人知的静态嵌套接口
- 如果内部类不需要访问外部实例,请优先使用静态嵌套类
常见问题解答
「静态嵌套类」课时是免费的吗?
是的 — 「静态嵌套类」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Java Academy 课程的其余内容,请升级到 CoddyKit PRO。 Java Academy 课程共包含 4 节课。
「静态嵌套类」这节课中我会学到什么?
定义静态嵌套类,将其作为关联的辅助类型,且不依赖外部类实例引用 你通过在浏览器中直接运行的动手代码来练习 Java Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Java Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Java Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。
「静态嵌套类」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Java Academy 课中编写并运行代码吗?
能。每节 Java Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。