Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Inheritance vs Composition
继承与组合

What you’ll learn: Why Rust favors composition over class inheritance and how Java design patterns change under that pressure.
本章将学习: 为什么 Rust 明显偏向组合而不是类继承,以及 Java 设计模式在这种压力下会怎么变形。

Difficulty: 🟡 Intermediate
难度: 🟡 中级

Rust has no class inheritance. That is not a missing feature by accident; it is a design decision.
Rust 没有类继承,这不是漏掉了什么,而是刻意的设计选择。

What Replaces Inheritance
什么东西替代了继承

  • traits for shared behavior
    trait 承载共享行为。
  • structs for data ownership
    struct 承载数据所有权。
  • delegation for reuse
    委托负责复用。
  • enums for explicit variant modeling
    enum 负责显式的分支建模。

Why This Helps
这样做有什么好处

Inheritance-heavy code often mixes state sharing, behavioral polymorphism, and framework convenience into one mechanism. Rust separates those concerns, which can make designs flatter and easier to audit.
重继承代码经常把状态共享、行为多态和框架便利性揉进一个机制里。Rust 则会把这些关注点拆开,所以设计通常更扁平,也更容易审计。

Advice for Java Developers
给 Java 开发者的建议

  • model behavior with traits
    行为抽象优先用 trait。
  • reuse implementation through helper types and delegation
    实现复用优先靠辅助类型和委托。
  • use enums where inheritance trees only exist to model variants
    如果继承树只是为了表示“几种变体”,那大概率该换成 enum。

Composition in Rust is usually less magical and more honest about where behavior really lives.
Rust 里的组合通常更少魔法,也更诚实地表达“行为到底放在哪”。