First exams 2027 · HL only2027 年首次开考 · 仅 HL

B3.2.1 · Fundamentals of OOP for multiple classes (HL)

B3.2.1 · 多个类的 OOP 基础(HL)

Inheritance and code reusability

继承与代码复用

Writing the shared part once, then letting specialised classes take it and build on top of it.

把共同的部分只写一次,再让专门化的类拿去,在其基础上继续构建。

HL only Typically 4–6 marks · AO2/AO3 Command terms: explain, apply
仅 HL 通常 4–6 分 · AO2/AO3 指令词:explain, apply

Explainer

讲解

Ravensworth Climbing Centre logs every route on its walls. A boulder problem and a roped route are genuinely different things: one records the depth of matting underneath it, the other records how many bolts it has and whether it runs over more than one pitch. But both have a route code, a grade, the name of whoever set it, and a count of how many times it has been climbed. Writing two separate classes means writing that shared half twice, and fixing every future bug in it twice.

Ravensworth 攀岩中心为墙上的每一条路线做记录。抱石路线和绳索路线确实是不同的东西:前者记录下方垫子的厚度,后者记录有多少个挂点,以及是否跨越多于一段绳距。但两者都有路线编号、难度等级、定线者的名字,以及被攀爬过多少次的计数。写两个独立的类,就意味着把这共同的一半写两遍,将来修复其中的每个错误也要修两遍。

Df

Inheritance lets a new class start from an existing one, automatically receiving its attributes and methods, so that only the differences have to be written. The shared code lives in one place and is reused rather than repeated.

继承(inheritance)让一个新类从一个现有的类出发,自动获得它的属性和方法,这样只需要写出不同的部分。共同的代码放在一个地方,被复用而不是重复。

Df

The class being inherited from is the parent class (also called the superclass or base class). The class doing the inheriting is the child class (also called the subclass or derived class). The relationship is hierarchical: children sit below their parent, and a child can itself be the parent of another class further down.

被继承的类是父类(也叫超类或基类)。进行继承的类是子类(也叫派生类)。这种关系是层次式的:子类位于父类之下,而子类自己也可以成为再往下的另一个类的父类。

The test for whether inheritance is the right tool is the is-a question. A boulder problem is a route, so BoulderRoute inheriting from Route is sound. A climbing wall is not a route, it has routes, so that relationship is not inheritance at all.

判断继承是不是合适工具的测试,是 is-a(是一个)问题。一条抱石路线是一条路线,所以让 BoulderRoute 继承 Route 是合理的。一面攀岩墙不是路线,它拥有路线,所以这种关系根本不是继承。

Worked example

例题讲解

One parent, two children

一个父类,两个子类

Everything in the parent is available to both children without being rewritten. The greyed italic rows below are not typed out again in the child classes, they arrive automatically.

父类中的一切,两个子类都能直接使用,无需重写。下面灰色斜体的行在子类中没有重新写出来,它们是自动到来的。

The hollow triangle always points at the parent.

空心三角形总是指向父类。

Route
+ code : string
+ grade : string
# timesClimbed : int
− inspectionLog : string
+ logClimb()
+ describe() : string
BoulderRoute
+ code, grade
# timesClimbed
+ matDepth : int
+ logClimb()
+ describe() : string
RopeRoute
+ code, grade
# timesClimbed
+ bolts : int
+ logClimb()
+ describe() : string
+ public # protected − private italic grey inherited, not rewritten
+ public 公有 # protected 受保护 − private 私有 灰色斜体 继承而来,未重写

Notice what is not italic in the children: matDepth and bolts are the genuinely new parts, and describe() appears in both children in normal type because each one replaces the parent's version with its own. That replacement is called overriding.

注意子类中哪些不是斜体:matDepth 和 bolts 是真正新增的部分,而 describe() 在两个子类中都以正常字体出现,因为各自用自己的版本替换了父类的版本。这种替换叫做重写(overriding)。

Explainer

讲解

Reusing, and then extending

先复用,再扩展

Inheritance is not only about taking a copy. A child normally does three things: it accepts what it wants unchanged, it adds what is new, and it replaces what needs to behave differently.

继承不只是拿一份拷贝。子类通常做三件事:接受它想要原样保留的部分,添加新的部分,并替换需要有不同行为的部分。

# the shared half, written once
class Route:
    def __init__(self, code, grade, setter):
        self.code = code
        self.grade = grade
        self._times_climbed = 0          # protected by convention
        self.__inspection_log = "clear"   # private to Route

    def log_climb(self):
        self._times_climbed += 1

    def describe(self):
        return f"{self.code} ({self.grade})"


class BoulderRoute(Route):          # inherits everything above
    def __init__(self, code, grade, setter, mat_depth):
        super().__init__(code, grade, setter)   # run the parent's setup first
        self.mat_depth = mat_depth               # ADD what is new

    def describe(self):                       # REPLACE the parent's version
        return super().describe() + f", {self.mat_depth}cm matting"
// the shared half, written once
public class Route {
    public String code;
    public String grade;
    protected int timesClimbed;        // reachable by subclasses
    private String inspectionLog;      // NOT reachable by subclasses

    public void logClimb() {
        timesClimbed++;
    }

    public String describe() {
        return code + " (" + grade + ")";
    }
}

public class BoulderRoute extends Route {   // inherits everything above
    public int matDepth;

    public BoulderRoute(String code, String grade, int matDepth) {
        super(code, grade);            // run the parent's constructor first
        this.matDepth = matDepth;      // ADD what is new
    }

    @Override
    public String describe() {         // REPLACE the parent's version
        return super.describe() + ", " + matDepth + "cm matting";
    }
}

Python marks inheritance with parentheses after the class name; Java uses the extends keyword. Both call the parent's constructor first through super, because the parent's own setup has to finish before the child adds anything of its own.

Python 在类名后加括号来表示继承;Java 使用 extends 关键字。两者都先通过 super 调用父类的构造方法,因为在子类添加自己的东西之前,父类自己的设置必须先完成。

The reusability point examiners want考官想看到的复用要点

log_climb() is written once, in Route. Both children get it, and a third route type added next year gets it too, with no new code. If the counting rule ever changes, it changes in exactly one place rather than in every route class that exists.

log_climb() 只在 Route 中写了一次。两个子类都得到它,明年新增的第三种路线类型也会得到它,不需要任何新代码。如果计数规则变了,只需在一个地方修改,而不是在每一个路线类里都改。

Worked example

例题讲解

Where a method is actually found

方法究竟在哪里被找到

Calling boulder.log_climb() works even though BoulderRoute never defines it. Step through what the interpreter does to find it.

调用 boulder.log_climb() 能成功,尽管 BoulderRoute 从未定义它。一步一步看解释器是如何找到它的。

Following the chain upwards Step 1 of 4
沿着继承链向上查找 第 1 步,共 4 步

Step 1. The call is made on a child object. boulder was built from BoulderRoute, so that is where the search starts.

第 1 步。在子类对象上发出调用。boulder 是由 BoulderRoute 创建的,所以查找从那里开始。

boulder.log_climb()

Step 2. Look on the child class first. BoulderRoute defines __init__ and describe, but no log_climb. The search does not stop here, it moves up.

第 2 步。先在子类上找。BoulderRoute 定义了 __init__ 和 describe,但没有 log_climb。查找并不会在这里停下,而是继续向上。

BoulderRoute: __init__ describe no log_climb

Step 3. Move up to the parent. Route does define log_climb, so the search stops here. This is the whole mechanism behind reuse: nothing was copied into the child, the lookup simply continues upwards.

第 3 步。向上移到父类。Route 确实定义了 log_climb,所以查找在这里停止。这就是复用背后的全部机制:没有任何东西被复制到子类里,只是查找继续向上进行。

BoulderRoute: __init__ describe no log_climb Route: log_climb describe found

Step 4. Run it, with self still the child object. The method lives on Route, but it operates on the boulder object, so it is that object's own counter that goes up. Had BoulderRoute defined its own log_climb, the search would have stopped at Step 2 and the parent's version would never have run: that is what overriding means.

第 4 步。运行它,self 仍然是那个子类对象。这个方法定义在 Route 上,但它作用于 boulder 对象,所以增加的是那个对象自己的计数器。如果 BoulderRoute 定义了自己的 log_climb,查找会在第 2 步就停下,父类的版本永远不会运行:这就是重写的含义。

Route.log_climb(self = the BoulderRoute object) self._times_climbed += 1 # the boulder's own count, now 1

Explainer

讲解

What a child can and cannot reach

子类能访问什么,不能访问什么

Inheriting a class does not mean inheriting permission to touch all of it. Each access modifier answers the question differently, and this is the part of the statement most often examined. Click through all four.

继承一个类,并不意味着继承了触碰它所有部分的权限。每种访问修饰符的回答各不相同,这也是这条陈述最常被考到的部分。把四种都点一遍。

The child class

子类

Unrelated outside code

无关的外部代码

Java:
Python:
The one that catches people out最容易让人栽跟头的一点

Private members are inherited, but not accessible. A BoulderRoute object really does carry the parent's private inspection log inside it, and the parent's own public methods can still read it. What the child class cannot do is write code that touches it directly. Inherited and reachable are two different things, and saying "private members are not inherited" is the version that loses the mark.

私有成员会被继承,但不可访问。一个 BoulderRoute 对象内部确实带着父类的私有检查日志,父类自己的公有方法仍然可以读取它。子类做不到的,是写代码直接去碰它。"被继承"和"可访问"是两回事,而说"私有成员不会被继承"正是会丢分的那种说法。

Try it yourself

动手试试

Test the boundary yourself

亲自测试这条边界

The Ravensworth classes, live and editable. The last line is commented out on purpose: uncomment it to watch a child class get refused access to its own parent's private attribute.

Ravensworth 的这些类,可在线编辑运行。最后一行故意被注释掉了:取消注释,观察子类如何被拒绝访问它自己父类的私有属性。

main.py
Loading Python engine…
Output
输出
Press Run to see the output here.

Running in offline fallback mode. The full Python engine couldn't load (blocked school network, or no internet), so this console switched automatically to a small hand-written engine. It runs this page's scenario, including inheritance, super() and the private-versus-protected boundary, but it isn't full Python.

正在使用离线备用模式。完整的 Python 引擎未能加载(可能是学校网络被屏蔽,或没有网络),所以这个控制台自动切换到了一个手写的小型引擎。它能运行本页的场景,包括继承、super() 以及 private 与 protected 的边界,但它不是完整的 Python。

Check your understanding

检查你的理解

Route declares inspectionLog as private and timesClimbed as protected. Inside BoulderRoute, which of these is true?

Route 把 inspectionLog 声明为 private,把 timesClimbed 声明为 protected。在 BoulderRoute 内部,下面哪一项为真?

Common mistake

常见错误

Markers reported this pattern for B3.2.1
阅卷员反馈了 B3.2.1 的这一常见模式

RecurringCandidates state that private members are not inherited. They are: the child object genuinely contains them, and the parent's own public methods can still operate on them. What the child class cannot do is refer to them directly in its own code. Answers that confuse inherited with accessible lose the mark even when the surrounding explanation is sound.

反复出现考生写"私有成员不会被继承"。其实它们会:子类对象确实包含它们,父类自己的公有方法仍然可以对它们操作。子类做不到的,是在自己的代码里直接引用它们。把被继承与可访问混为一谈的答案,即使其余解释没问题,也会丢分。

The second recurring error is on reusability questions: describing inheritance as "it saves typing." The creditworthy version names the maintenance consequence, that shared behaviour is defined once so a change to it happens in one place.

第二个反复出现的错误出现在复用性的题目里:把继承描述成"它能省去打字"。能得分的说法要点出维护方面的后果,即共同的行为只定义一次,所以对它的修改只发生在一个地方。

Answer frame that scores: name the modifier → say whether the child may access it directly → say what still happens to the member regardless.

能得分的答题框架:指出修饰符 → 说明子类能否直接访问它 → 说明无论如何这个成员仍然会发生什么。

✕

What a weak answer looks like: “Private variables are not inherited by the subclass, so BoulderRoute does not have inspectionLog.” The second half is simply untrue, and it is the half that decides the mark.

较弱的答案是这样的:“私有变量不会被子类继承,所以 BoulderRoute 没有 inspectionLog。”后半句根本不对,而恰恰是后半句决定了得分。

✓

What it should say: “inspectionLog is private, so although every BoulderRoute object contains it, code written inside BoulderRoute cannot access it directly and must go through a public method of Route. timesClimbed is protected, so BoulderRoute can use it directly.” Modifier named, access stated, and the distinction between holding and reaching made explicit.

应该这样写:“inspectionLog 是私有的,所以尽管每个 BoulderRoute 对象都包含它,写在 BoulderRoute 内部的代码也不能直接访问它,必须通过 Route 的一个公有方法。timesClimbed 是 protected,所以 BoulderRoute 可以直接使用它。”指出了修饰符,说明了访问情况,并且明确区分了"持有"和"够得着"。

Revision questions

复习题

Past-paper style. Write an answer, then reveal the marking points and mark yourself.

仿真题风格。先写出你的答案,再显示评分要点并给自己打分。

Question 1 · 2 marks第 1 题 · 2 分

[2]Identify the parent class and one child class in the Ravensworth hierarchy, and state one attribute the child receives without declaring it.

[2]指出 Ravensworth 层次结构中的父类和一个子类,并说明子类在没有声明的情况下得到的一个属性。

Question 2 · 4 marks第 2 题 · 4 分

[4]The centre adds indoor speed lanes, which have a route code, a grade and a climb count like every other route, plus a recorded fastest time. Construct the class, using inheritance.

[4]中心新增了室内速度赛道,它和其他每条路线一样有路线编号、难度等级和攀爬计数,另外还记录最快时间。使用继承来构建这个类。

Question 3 · 3 marks第 3 题 · 3 分

[3]RopeRoute needs to read inspectionLog, which is private in Route. Explain why it cannot do so directly, and outline one way to give it proper access.

[3]RopeRoute 需要读取 inspectionLog,而它在 Route 中是 private。解释为什么它不能直接读取,并概述一种给它合适访问权限的方法。

Flashcards

闪卡

Active recall for this statement’s key terms.

针对本条陈述关键术语的主动回忆。

Prototype render · content grounded in real IB CS 2027 marker-report data for B3.2.1 · not yet wired to live routes