B3.2.2 · Fundamentals of OOP for multiple classes (HL)
B3.2.2 · 多个类的 OOP 基础(HL)
Polymorphism and method overriding
多态与方法重写
One instruction, sent to many different kinds of object, and each one answers it in the way that is right for itself.
同一条指令,发给许多不同种类的对象,每个对象都以对自己合适的方式回应。
Explainer
讲解
Kirkstall Print Works runs one queue for everything it prints: posters, stapled booklets, cut-out stickers. When the manager presses "quote this queue", every job has to produce a price, but no two job types are priced the same way. Posters go by sheet, booklets by page count times copies, stickers add a fixed die-cutting fee on top. The queue code should not have to know any of that. It should ask each job for its price and trust the job to answer correctly.
Kirkstall 印刷厂用同一个队列处理所有印刷品:海报、装订小册子、模切贴纸。经理按下"为这个队列报价"时,每个任务都必须给出价格,但没有两种任务的计价方式相同。海报按张数计价,小册子按页数乘以份数,贴纸还要另加一笔固定的模切费。队列代码不应该需要知道这些。它应该向每个任务询问价格,并相信任务会正确回答。
Polymorphism (from the Greek for "many forms") is the ability of objects of different classes to respond to the same method call, each in the way appropriate to its own class. The caller uses one name; which code actually runs depends on the object.
多态(polymorphism)(源自希腊语,意为"多种形态")是指不同类的对象对同一个方法调用做出回应,每个对象按各自所属类合适的方式回应的能力。调用者使用同一个名字;真正运行哪段代码,取决于对象本身。
This is what makes the queue loop flexible and the code reusable: one loop handles every job type that exists today, and keeps working unchanged for every job type added later. Without it, that loop would be a growing chain of type checks that has to be edited every time the business offers something new.
这使得队列循环更灵活,代码更可复用:一个循环就能处理今天存在的每一种任务类型,并且对以后新增的每一种任务类型也无需修改。没有它,这个循环就会变成一条越来越长的类型检查链,每次业务推出新东西都要修改。
Explainer
讲解
Two forms, decided at two different times
两种形式,在两个不同的时间做出决定
The syllabus asks for both. They share the "one name, several behaviours" idea, but they differ in when the decision about which code to run gets made.
考纲要求两者都要掌握。它们共享"一个名字,多种行为"的思想,但在何时决定运行哪段代码上有所不同。
Dynamic (runtime) polymorphism is achieved by method overriding. A child class provides its own version of a method that already exists in its parent, with the same name and the same parameters. Which version runs is decided while the program is running, based on what the object actually is.
动态(运行时)多态通过方法重写(overriding)实现。子类为父类中已有的方法提供自己的版本,方法名相同,参数也相同。运行哪个版本,是在程序运行期间,根据对象实际是什么来决定的。
Static (compile-time) polymorphism is achieved by method overloading. One class provides several methods sharing a name but taking different parameter lists. Which version runs is decided before the program ever runs, by matching the arguments at the call site to a signature.
静态(编译时)多态通过方法重载(overloading)实现。一个类提供几个同名但参数列表不同的方法。运行哪个版本,是在程序运行之前,通过把调用处的实参与某个签名匹配来决定的。
Overriding: same name, same parameters, different class, chosen at runtime. Overloading: same name, different parameters, same class, chosen at compile time. Mixing these two up is the single most common error on this statement.
重写:方法名相同,参数相同,类不同,在运行时选择。重载:方法名相同,参数不同,类相同,在编译时选择。把这两者弄混,是这条陈述上最常见的单一错误。
Worked example
例题讲解
Dynamic polymorphism: overriding estimate_cost()
动态多态:重写 estimate_cost()
Each job type replaces the parent's pricing method with its own. Note that every version has an identical signature, which is exactly what makes it overriding rather than overloading.
每种任务类型都用自己的计价方法替换父类的计价方法。注意每个版本的签名都完全相同,这正是它属于重写而不是重载的原因。
# the shared shape, and a fallback price class PrintJob: def __init__(self, ref, copies): self.ref = ref self.copies = copies def estimate_cost(self): return self.copies * 0.10 class PosterJob(PrintJob): def estimate_cost(self): # SAME name, SAME parameters return self.copies * 2.50 class BookletJob(PrintJob): def __init__(self, ref, copies, pages): super().__init__(ref, copies) self.pages = pages def estimate_cost(self): # SAME name, SAME parameters return self.copies * self.pages * 0.08
// the shared shape, and a fallback price public class PrintJob { protected String ref; protected int copies; public double estimateCost() { return copies * 0.10; } } public class PosterJob extends PrintJob { @Override public double estimateCost() { // SAME name, SAME parameters return copies * 2.50; } } public class BookletJob extends PrintJob { private int pages; @Override public double estimateCost() { // SAME name, SAME parameters return copies * pages * 0.08; } }
Java marks the intention with @Override. It is optional, but it asks the compiler to check that a method with this exact signature really does exist in the parent, which turns a silent typo into a caught error.
Java 用 @Override 来标明意图。它是可选的,但它会要求编译器检查父类中是否真的存在具有这个确切签名的方法,从而把一个悄无声息的拼写错误变成能被捕获的错误。
Worked example
例题讲解
One call, three different answers
一次调用,三个不同的答案
The quoting loop is four lines long and mentions no job type at all.
报价循环只有四行,而且完全没有提到任何任务类型。
# the queue holds three different classes, and the loop knows about none of them queue = [PosterJob("KP-118", 6), BookletJob("KP-119", 25, 12), StickerJob("KP-120", 40)] for job in queue: print(job.ref, job.estimate_cost())
Click a job in the queue to see which class’s method actually ran.
点击队列中的一个任务,看看实际运行的是哪个类的方法。
Object’s class
对象所属的类
Method that runs
实际运行的方法
Result
结果
Adding a fourth job type next year means writing one new class. The quoting loop, the invoice printer, and every other place that walks the queue keep working untouched, because none of them ever asked what kind of job they were holding.
明年新增第四种任务类型,只需要写一个新类。报价循环、发票打印程序,以及其他所有遍历队列的地方都不用动,因为它们从来没有问过自己手里拿着的是哪种任务。
Explainer
讲解
Static polymorphism: overloading
静态多态:重载
The print works also wants two ways to ask for a quote: the plain one, and one that applies a rush surcharge. Same idea, same name, different information supplied.
印刷厂还希望有两种询价方式:普通的,以及加急附加费的。想法相同,名字相同,只是提供的信息不同。
In Java, this is real overloading
在 Java 中,这是真正的重载
// three methods, one name, three different parameter lists public class Quote { public double total(int copies) { return copies * 0.10; } public double total(int copies, boolean rush) { return copies * 0.10 * (rush ? 2 : 1); } public double total(int copies, int pages) { return copies * pages * 0.08; } } // the compiler picks the right one from the arguments, before the program runs q.total(40); // 4.00 picks version 1 q.total(40, true); // 8.00 picks version 2 q.total(25, 12); // 24.00 picks version 3
This is where the efficiency comes from: the decision costs nothing at runtime because it was already made during compilation, and callers get one obvious name to remember instead of totalPlain, totalRush and totalByPage.
效率就来自这里:这个决定在运行时没有任何开销,因为它在编译期间就已经做出了,而且调用者只需要记住一个明显的名字,而不是 totalPlain、totalRush 和 totalByPage。
In Python, it is not
在 Python 中,不是这样
Writing two methods with the same name does not give you two methods. The second definition simply replaces the first, silently, with no error. Python decides what to call by name alone, so a name can only ever refer to one thing at a time.
写两个同名的方法,并不会得到两个方法。第二个定义会悄悄地替换第一个,没有任何错误提示。Python 只根据名字来决定调用什么,所以一个名字在同一时间只能指向一样东西。
# this does NOT create two versions class Quote: def total(self, copies): return copies * 0.10 def total(self, copies, rush): # this REPLACES the one above return copies * 0.10 * (2 if rush else 1) q = Quote() q.total(40, True) # 8.00, this works q.total(40) # TypeError: the first version no longer exists
Python reaches the same goal a different way: one method with default parameter values, so the caller may supply the extra information or leave it out.
Python 用另一种方式达到同样的目标:一个带有默认参数值的方法,调用者可以提供额外的信息,也可以省略。
# one method, several ways to call it: Python's answer to overloading class Quote: def total(self, copies, pages=1, rush=False): cost = copies * pages * 0.08 if pages > 1 else copies * 0.10 return cost * 2 if rush else cost q.total(40) # 4.00 q.total(40, rush=True) # 8.00 q.total(25, 12) # 24.00
Same three call shapes, same three answers, one definition. If a question asks you to apply static polymorphism and you are writing Python, say plainly that Python has no true overloading and show the default-parameter equivalent: that earns the mark, whereas two identical method names does not.
同样三种调用形式,同样三个答案,只有一个定义。如果题目要求你应用静态多态,而你写的是 Python,要明确说明 Python 没有真正的重载,并给出用默认参数实现的等价写法:这能得分,而写两个相同的方法名则不能。
Explainer
讲解
Comparing the two forms
比较这两种形式
Real example: PosterJob.estimate_cost() replacing PrintJob.estimate_cost(), chosen when the loop reaches that object.
实际例子:PosterJob.estimate_cost() 替换 PrintJob.estimate_cost(),在循环处理到那个对象时选择。
Advantage
优点
- New types plug in without touching existing code (the quoting loop never changes, so adding a job type cannot break the jobs that already work)
- 新类型可以直接接入而不用改动已有代码 (报价循环永远不变,所以新增任务类型不会破坏已经能用的任务)
Disadvantage
缺点
- Harder to follow when reading (the line says estimate_cost(), but which of four versions runs is only knowable at runtime, so a debugger is often needed to be sure)
- 阅读时更难理解 (这一行写的是 estimate_cost(),但四个版本中运行哪一个,只有在运行时才能知道,所以常常需要用调试器才能确定)
Real example: total(copies) and total(copies, rush) in the same Java class, chosen by the compiler.
实际例子:同一个 Java 类中的 total(copies) 和 total(copies, rush),由编译器选择。
Advantage
优点
- No runtime cost and one name to learn (the choice is fixed during compilation, and callers avoid memorising three near-identical method names)
- 没有运行时开销,只需学一个名字 (选择在编译期间就固定了,调用者也不必记住三个几乎一样的方法名)
Disadvantage
缺点
- Fixed at compile time, and not universal (it cannot adapt to what an object turns out to be, and Python does not offer it at all)
- 在编译时就固定,而且并非通用 (它无法适应对象最终实际是什么,而且 Python 根本不提供它)
Try it yourself
动手试试
Watch the right version get chosen
观察正确的版本是如何被选中的
The Kirkstall classes, live and editable. Two experiments worth running: add a fourth job class to the queue without touching the loop, and uncomment the final block to watch Python quietly discard a method when you try to overload it.
Kirkstall 的这些类,可在线编辑运行。有两个值得做的实验:在不改动循环的情况下,给队列再加一个任务类;以及取消最后一段代码的注释,看 Python 如何在你尝试重载时悄悄丢弃一个方法。
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 overriding, dynamic dispatch and Python’s replace-not-overload behaviour, but it isn’t full Python.
正在使用离线备用模式。完整的 Python 引擎未能加载(可能是学校网络被屏蔽,或没有网络),所以这个控制台自动切换到了一个手写的小型引擎。它能运行本页的场景,包括重写、动态分派以及 Python "替换而非重载"的行为,但它不是完整的 Python。
Check your understanding
检查你的理解
A class defines total(int copies) and total(int copies, boolean rush). A subclass then defines total(int copies) again. Which forms of polymorphism are present?
一个类定义了 total(int copies) 和 total(int copies, boolean rush)。随后一个子类又定义了 total(int copies)。其中存在哪些形式的多态?
Common mistake
常见错误
B3.2.2B3.2.2 的这一常见模式RecurringOverriding and overloading are swapped constantly. Because the words look alike, candidates describe one and name the other, and the mark is lost on the label rather than on the understanding. The deciding detail is the parameter list: identical means overriding, different means overloading.
反复出现重写和重载总是被互换。因为两个词看起来相似,考生描述的是一个,写出的名称却是另一个,丢分丢在名称上,而不是丢在理解上。决定性的细节是参数列表:相同是重写,不同是重载。
A second error appears in Python answers: writing two methods with the same name and different parameters, and calling it overloading. Python accepts the code, so it looks right, but only the second definition survives.
第二个错误出现在 Python 的答案里:写了两个同名但参数不同的方法,并称之为重载。Python 接受这段代码,所以看起来是对的,但只有第二个定义保留了下来。
Answer frame that scores: name the mechanism → state whether the parameter lists match → say when the choice is made, at compile time or at runtime.
能得分的答题框架:指出机制 → 说明参数列表是否一致 → 说明选择是在何时做出的,是编译时还是运行时。
What a weak answer looks like: “PosterJob overloads estimate_cost() so it can calculate its own price.” The mechanism described is right, the name given to it is wrong, and it is the name being examined.
较弱的答案是这样的:“PosterJob 重载了 estimate_cost(),这样它就能计算自己的价格。”描述的机制是对的,给它起的名称却是错的,而被考查的恰恰就是这个名称。
What it should say: “PosterJob overrides estimate_cost(): it declares the method with the same name and the same parameters as PrintJob, so at runtime the version belonging to the actual object is the one that executes.” Mechanism named, signature stated, timing given.
应该这样写:“PosterJob 重写了 estimate_cost():它用与 PrintJob 相同的方法名和相同的参数声明这个方法,所以在运行时,执行的是实际对象所属的那个版本。”点出了机制,说明了签名,给出了时机。
Revision questions
复习题
Past-paper style. Write an answer, then reveal the marking points and mark yourself.
仿真题风格。先写出你的答案,再显示评分要点并给自己打分。
[2]Using the Kirkstall queue, distinguish between method overriding and method overloading.
[2]以 Kirkstall 队列为例,区分方法重写和方法重载。
Marking points
评分要点
- Method overriding: a subclass in the Kirkstall queue redefines a method it inherited, keeping the same name and parameters but giving its own behaviour.
- Method overloading: defining several methods with the same name but different parameter lists, chosen by the arguments supplied.
- Overriding replaces an inherited method; overloading provides same-named variants with different signatures.
- 方法重写:Kirkstall 队列中的一个子类重新定义了一个它继承来的方法,保持相同的名称和参数,但给出自己的行为。
- 方法重载:定义几个同名但形参列表不同的方法,由所提供的实参决定用哪个。
- 重写替换一个继承来的方法;重载提供签名不同的同名变体。
[4]The print works adds laminated menus, priced at 1.20 per copy plus a fixed 6.00 setup charge. Construct the class so the existing quoting loop prices it without modification.
[4]印刷厂新增了覆膜菜单,每份 1.20,另加固定的 6.00 设置费。构建这个类,使现有的报价循环无需修改就能为它计价。
Marking points
评分要点
- class LaminatedMenu inherits from the same base class as the other quoted items.
- It overrides the pricing method (the one the quoting loop calls) with its own formula: 1.20 per copy plus a fixed 6.00 setup charge.
- Because it exposes the same method name and signature, the existing loop calls it polymorphically with no change.
- The constructor takes the copy count (and any shared attributes via the parent constructor).
- class LaminatedMenu 从与其他报价项相同的基类继承。
- 它用自己的公式重写定价方法(报价循环所调用的那个):每份 1.20 加上固定的 6.00 设置费。
- 因为它公开相同的方法名和签名,现有循环通过多态调用它,无需改动。
- 构造函数接收份数(以及通过父类构造函数接收任何共享属性)。
[3]A student writes two Python methods named total() with different parameter lists and states that this demonstrates static polymorphism. Explain why this is incorrect, and describe what Python does instead.
[3]一位学生写了两个名为 total() 的 Python 方法,参数列表不同,并声称这演示了静态多态。解释为什么这是不对的,并描述 Python 实际上是怎么做的。
Marking points
评分要点
- Python does not support true overloading: when two methods named total() are defined, the second definition simply replaces the first.
- So only the last total() exists, and calling it with the wrong number of arguments is an error, not a second overload.
- Also, overloading is resolved at compile time in languages that have it, which is compile-time (static) polymorphism, but Python resolves calls at run time.
- Python instead uses default parameter values or a variable-length argument list to let one method handle different argument counts.
- Python 不支持真正的重载:当定义了两个名为 total() 的方法时,第二个定义直接替换第一个。
- 所以只有最后一个 total() 存在,用错误数量的参数调用它是一个错误,而不是第二个重载。
- 此外,在支持重载的语言中重载是在编译时解决的,那是编译时(静态)多态,而 Python 在运行时解决调用。
- Python 转而用默认形参值或可变长度的参数列表,让一个方法处理不同的参数数量。
Flashcards
闪卡
Active recall for this statement’s key terms.
针对本条陈述关键术语的主动回忆。
Keep this statement’s practice with you
把本条陈述的练习带在身边
Free account: unlock every revision question and flashcard for B3.2.2, and every other IB CS 2027 statement.
免费账号:解锁 B3.2.2 以及其他所有 IB CS 2027 陈述的全部复习题和闪卡。