📚 IB OCR Computer Science: Object-Oriented Programming Key Concepts Explained | IB OCR 计算机:面向对象 考点精讲
Object-Oriented Programming (OOP) forms a central pillar of the IB and OCR Computer Science curricula. This revision guide breaks down the essential OOP principles, design techniques, and common examination pitfalls into clear, bilingual explanations to help you master the topic. Whether you are preparing for Paper 2 or the internal assessment, a solid grasp of classes, objects, inheritance, and polymorphism will be indispensable.
面向对象编程(OOP)是 IB 和 OCR 计算机科学课程的核心支柱。这份复习指南将重点面向对象原则、设计技巧和常见考试陷阱分解为中英双语清晰讲解,帮助你掌握该专题。无论你是在备考 Paper 2 还是准备内部评估,扎实掌握类、对象、继承和多态等概念都不可或缺。
1. Classes and Objects | 类与对象
A class is a blueprint or template that defines the attributes (data) and methods (behaviours) common to all objects of a certain kind. It does not occupy memory until an object is instantiated.
类是定义某一类对象共有属性(数据)和方法(行为)的蓝图或模板。在实例化对象之前,类不占用内存。
An object is a specific instance of a class with its own state. For example, Student alice = new Student("Alice", 17) creates an object alice of class Student. Each object stores its own copy of instance variables.
对象是类的一个特定实例,拥有自己的状态。例如,Student alice = new Student("Alice", 17) 创建了 Student 类的一个对象 alice。每个对象存储一份自己的实例变量副本。
- Attributes: instance variables (fields) such as name, age.
- Methods: functions that operate on the object's data, e.g.,
getAge().
- 属性:实例变量(字段),如姓名、年龄。
- 方法:操作对象数据的函数,如
getAge()。
Exam questions often ask you to identify a class from a scenario, draw its UML representation, or write simple instantiation code. OCR pseudocode uses CLASS Student ... ENDCLASS, while IB may use Java or Python conventions.
考试常要求根据场景识别类、绘制 UML 表示或编写简单的实例化代码。OCR 伪代码使用 CLASS Student ... ENDCLASS,而 IB 可能采用 Java 或 Python 语法。
2. Encapsulation | 封装
Encapsulation is the bundling of data with the methods that operate on that data, while restricting direct access to some of an object's components. This is typically achieved using access modifiers: private for fields and public for methods that provide controlled access.
封装是将数据与操作数据的方法捆绑在一起,同时限制对对象某些组件的直接访问。通常通过访问修饰符实现:字段使用 private,方法使用 public 以提供受控访问。
By making instance variables private and providing public getters and setters, you protect data integrity. For example, a setTemperature(double t) method can validate that the value is above absolute zero before assigning it.
通过将实例变量设为私有并公开 getter 和 setter,你可以保护数据完整性。例如,setTemperature(double t) 方法可以在赋值前验证该值是否高于绝对零度。
Encapsulation = Data Hiding + Controlled Interface
封装 = 数据隐藏 + 受控接口
In both IB and OCR, you must be able to explain why encapsulation is crucial for maintainability and to prevent unintended interference. The term "information hiding" is often used synonymously.
在 IB 和 OCR 中,你必须能够解释封装为何对可维护性和防止意外干扰至关重要。"信息隐藏"一词常作为同义词使用。
3. Inheritance | 继承
Inheritance allows a class (subclass) to acquire the properties and methods of another class (superclass). It promotes code reuse and establishes a natural hierarchy. In Java or C#, the keyword extends is used; Python uses parentheses class Dog(Animal):.
继承允许一个类(子类)获取另一个类(超类)的属性和方法。它促进代码重用并建立自然层次结构。在 Java 或 C# 中,使用关键字 extends;Python 使用括号 class Dog(Animal):。
A subclass can add new attributes and methods, or override inherited ones to provide specialised behaviour. For example, a Vehicle superclass with startEngine() can be extended by Car and Motorcycle, each overriding startEngine() appropriately.
子类可以添加新的属性和方法,或者重写继承的方法以提供专门行为。例如,Vehicle 超类拥有 startEngine(),可被 Car 和 Motorcycle 扩展,每个子类均可按需重写 startEngine()。
Types of inheritance: single, multilevel, hierarchical. Note that some languages (like Java) do not support multiple inheritance of classes to avoid the "diamond problem", but they allow multiple inheritance through interfaces.
继承类型:单继承、多层继承、分层继承。注意,某些语言(如 Java)不支持类的多继承以避免"菱形问题",但允许通过接口实现多重继承。
You should be able to draw inheritance trees and predict the output of code involving super() calls. OCR pseudocode uses INHERITS keyword, while IB typically expects Java or Python syntax.
你应该能够绘制继承树,并能预测包含 super() 调用的代码输出。OCR 伪代码使用 INHERITS 关键字,而 IB 通常要求 Java 或 Python 语法。
4. Polymorphism | 多态
Polymorphism means "many forms". It allows objects of different classes to respond to the same method call in their own specific way. There are two main categories: compile‑time (method overloading) and run‑time (method overriding).
多态意味着"多种形态"。它允许不同类的对象以自己的特定方式响应相同的方法调用。主要有两类:编译时多态(方法重载)和运行时多态(方法重写)。
Method overloading: multiple methods in the same class share the same name but differ in parameters (number, type, or order). This is resolved at compile time. Example: add(int a, int b) and add(double a, double b).
方法重载:同一类中的多个方法具有相同名称但参数不同(数量、类型或顺序),在编译时解析。例如:add(int a, int b) 与 add(double a, double b)。
Method overriding: a subclass provides a specific implementation of a method already defined in its superclass. The method signature remains identical. The correct version is determined at run‑time based on the actual object type, enabling dynamic method dispatch.
方法重写:子类为超类中已定义的方法提供特定实现,方法签名保持不变。正确的版本在运行时根据实际对象类型确定,从而实现动态方法调度。
For example, an Animal reference pointing to a Dog object will call the Dog's speak() method. This is fundamental to abstraction and interface‑based programming. OCR and IB both test the distinction between overloading and overriding, often with tracing exercises.
例如,一个指向 Dog 对象的 Animal 引用将调用 Dog 的 speak() 方法。这是抽象和基于接口编程的基础。OCR 和 IB 都通过追踪练习题考查重载与重写的区别。
5. Abstraction and Interfaces | 抽象与接口
Abstraction focuses on hiding complex implementation details and exposing only the essential features of an object. This is achieved using abstract classes and interfaces.
抽象侧重于隐藏复杂的实现细节,仅暴露对象的基本特征。这通过抽象类和接口来实现。
An abstract class cannot be instantiated and may contain abstract methods (without a body) that subclasses must implement, as well as concrete methods. It defines a common base with partial implementation.
抽象类不能被实例化,可以包含抽象方法(无方法体)——子类必须实现这些方法——以及具体方法。它定义了一个具有部分实现的公共基础。
An interface is a pure contract that specifies a set of method signatures but provides no implementation (though Java 8+ allows default methods). A class can implement multiple interfaces, achieving a form of multiple inheritance.
接口是一个纯粹的契约,规定了一组方法签名但不提供实现(尽管 Java 8+ 允许默认方法)。一个类可以实现多个接口,从而实现一种多重继承。
Key distinctions for exams:
- Abstract class: can have state (fields), constructors, and non‑public members.
- Interface: only public abstract methods (traditionally), focuses on capabilities (e.g.,
Comparable,Serializable).
考试中的关键区别:
- 抽象类:可以有状态(字段)、构造器和非公开成员。
- 接口:传统上仅有公共抽象方法,侧重于能力(例如
Comparable、Serializable)。
IB Paper 2 often requires designing an interface or abstract class from a given scenario. OCR's pseudocode uses INTERFACE keyword explicitly.
IB Paper 2 常要求根据给定场景设计接口或抽象类。OCR 伪代码显式使用 INTERFACE 关键字。
6. Constructors and Destructors | 构造函数与析构函数
A constructor is a special method invoked automatically when an object is created. It initialises the object's state and has the same name as the class in Java, or __init__ in Python. Constructors can be overloaded to provide multiple ways of instantiation.
构造函数是创建对象时自动调用的特殊方法。它初始化对象的状态,在 Java 中与类同名,在 Python 中为 __init__。构造函数可重载以提供多种实例化方式。
A default constructor is provided by the compiler if no constructor is defined. Once you define a parameterised constructor, the default one is lost unless explicitly re‑declared. You can call a superclass constructor using super() (Java) or super().__init__() (Python).
如果未定义构造函数,编译器会提供默认构造函数。一旦定义了带参数的构造函数,默认构造函数将丢失,除非显式重新声明。可使用 super()(Java)或 super().__init__()(Python)调用超类构造函数。
Destructors/finalisers (e.g., finalize() in Java, __del__ in Python) are rarely required in modern OOP due to automatic garbage collection. However, you may see questions about resource cleanup in languages like C++. IB/OCR rarely go into depth on destructors.
在现代 OOP 中,由于自动垃圾回收,很少需要析构函数/终结器(如 Java 的 finalize()、Python 的 __del__)。但你可能在 C++ 等语言中遇到关于资源清理的题目。IB/OCR 很少深入考查析构函数。
Always check constructor chaining when an inheritance hierarchy is involved: the superclass constructor runs before the subclass constructor.
涉及继承层次时,务必检查构造函数链:超类构造函数先于子类构造函数执行。
7. Accessor and Mutator Methods | 访问器与修改器
Accessor methods (getters) return the value of a private field without modifying it. Mutator methods (setters) modify a private field, often with validation logic. Both together preserve encapsulation while allowing controlled external access.
访问器方法(getter)返回私有字段的值而不修改它。修改器方法(setter)修改私有字段,通常包含验证逻辑。两者共同维护封装性,同时允许受控的外部访问。
For example:
public void setAge(int age) {
if (age > 0) this.age = age;
}
public int getAge() {
return this.age;
}
例如:
public void setAge(int age) {
if (age > 0) this.age = age;
}
public int getAge() {
return this.age;
}
Some objects are designed to be immutable (no mutators). Once created, their state cannot change (e.g., String in Java). Immutability simplifies concurrent programming and prevents unexpected side effects.
某些对象被设计为不可变的(无修改器)。一旦创建,其状态不可更改(如 Java 中的 String)。不可变性简化了并发编程并防止意外的副作用。
Exam tip: when asked to write a class definition, always declare fields as private and provide appropriate accessor/mutator methods unless the specification states otherwise.
考试提示:当要求编写类定义时,始终将字段声明为 private,并提供合适的访问器/修改器方法,除非题目另有规定。
8. Relationships: Dependency, Aggregation, and Composition | 关系:依赖、聚合与组合
OOP models real‑world relationships. The three main types (beyond inheritance) are:
- Dependency: "uses‑a" relationship. A class depends on another class if it uses objects of that class as local variables, method parameters, or return types. It's the weakest relationship.
- Aggregation: "has‑a" relationship. One class contains a reference to another, but the contained object can exist independently. Represented by an empty diamond in UML.
- Composition: "part‑of" strong ownership. The contained object cannot exist without the container. Represented by a filled diamond. E.g., a
HousecontainsRooms; if the house is destroyed, rooms cease to exist conceptually.
面向对象编程对现实世界关系进行建模。三种主要关系(除继承外)如下:
- 依赖:"uses‑a" 关系。如果一个类将另一类的对象用作局部变量、方法参数或返回类型,则它依赖于那个类。这是最弱的关系。
- 聚合:"has‑a" 关系。一个类包含对另一个类的引用,但被包含的对象可以独立存在。在 UML 中用空心菱形表示。
- 组合:"part‑of" 强所有关系。被包含的对象不能脱离容器而存在。在 UML 中用实心菱形表示。例如,
House包含Room对象;如果房子被毁,房间在概念上也不复存在。
OCR pseudocode questions sometimes show lists of objects and ask you to identify the relationship. IB design questions may require justifying the choice between aggregation and composition.
OCR 伪代码题有时会展示对象列表,要求你识别关系。IB 设计题可能要求论证选择聚合还是组合的理由。
9. UML Class Diagrams | UML 类图
Unified Modeling Language (UML) class diagrams are essential for designing and documenting OOP systems. A class is drawn as a rectangle divided into three compartments: class name, attributes, and methods.
统一建模语言(UML)类图对于设计和文档化面向对象系统至关重要。类绘制为一个矩形,分为三个隔间:类名、属性和方法。
Visibility markers: + public, - private, # protected. Inheritance is shown with a hollow triangle arrow pointing to the superclass. Interfaces are represented with a dashed line and hollow triangle, or the «interface» stereotype.
可见性标记:+ 公共,- 私有,# 受保护。继承用空心三角形箭头指向超类表示。接口用虚线和空心三角形或 «interface» 构造型表示。
Relationships: association (solid line), aggregation (hollow diamond), composition (filled diamond). Dependencies are shown as dashed lines with an open arrow. Multiplicity is noted at each end (e.g., 1, 0..*, 1..*).
关系:关联(实线)、聚合(空心菱形)、组合(实心菱形)。依赖用虚线开箭头表示。多重性标注在两端(例如 1、0..*、1..*)。
Both OCR and IB exams frequently include a question where you must interpret or draw a UML diagram from a scenario description. Always label arrows and multiplicities carefully.
OCR 和 IB 考试经常包含根据场景描述解释或绘制 UML 图的题目。务必仔细标注箭头和多重性。
10. SOLID Design Principles | SOLID 设计原则
SOLID is a set of five design principles that help make software more understandable, flexible, and maintainable. While not always named directly, these concepts underpin many IB/OCR design questions:
SOLID 是一组五个设计原则,有助于使软件更易理解、更灵活、更易维护。虽然并非总是直接点名,但这些概念支撑着许多 IB/OCR 设计题:
- Single Responsibility: A class should have only one reason to change.
- Open/Closed: Classes should be open for extension but closed for modification.
- Liskov Substitution: Subtypes must be substitutable for their base types without altering correctness.
- Interface Segregation: Many client‑specific interfaces are better than one general‑purpose interface.
- Dependency Inversion: Depend on abstractions, not on concretions.
- Single Responsibility(单一职责):一个类应该有且只有一个引起它变化的原因。
- Open/Closed(开闭原则):类应对扩展开放,对修改封闭。
- Liskov Substitution(里氏替换):子类型必须能够替换其基类型而不影响正确性。
- Interface Segregation(接口隔离):多个客户端专用接口优于一个通用接口。
- Dependency Inversion(依赖倒置):依赖抽象,而非具体实现。
Applying SOLID reduces tight coupling, making unit testing and future changes easier. For example, using an interface PaymentGateway instead of coding directly to PayPalService allows swapping implementations without changing the dependent class.
应用 SOLID 能减少紧耦合,使单元测试和未来变更更容易。例如,使用接口 PaymentGateway 而不是直接编写 PayPalService,可在不更改依赖类的情况下替换实现。
In evaluation questions, you can gain high marks by discussing how adherence to these principles improves code quality.
在评估题中,讨论遵循这些原则如何提升代码质量可获得高分。
11. Advantages and Disadvantages of OOP | 面向对象编程的优缺点
Understanding the trade‑offs helps in justifying design choices and evaluating applications. Common advantages:
- Modularity: Classes are self‑contained, making development and debugging easier.
- Reusability: Inheritance and composition enable code reuse.
- Flexibility and maintainability: Polymorphism and abstraction allow changes with minimal impact.
- Real‑world modelling: Objects mirror real entities, aiding analysis and design.
理解其权衡有助于证明设计选择的合理性并评估应用程序。常见优点:
- 模块化:类是自包含的,方便开发和调试。
- 可重用性:继承和组合使代码得以重用。
- 灵活性和可维护性:多态和抽象使得变更的影响降到最低。
- 现实世界建模:对象映射现实实体,有助于分析与设计。
Disadvantages include:
- Steeper learning curve: Paradigm shift from procedural programming.
- Performance overhead: Object creation and method dispatch can be slightly slower than procedural equivalents.
- Over‑engineering: Simple problems may be over‑complicated with deep inheritance hierarchies.
- Resource consumption: Objects consume more memory than simple data structures.
缺点包括:
- 学习曲线陡峭:与过程式编程相比存在范式转换。
- 性能开销:对象创建和方法调度可能比过程式等价代码稍慢。
- 过度工程化:简单问题可能因深层继承层次而过度复杂。
- 资源消耗:对象比简单数据结构消耗更多内存。
Both OCR and IB require you to discuss appropriateness of OOP for a given problem, so citing a balanced set of pros and cons is essential.
OCR 和 IB 都要求你讨论面向对象编程对给定问题的适用性,因此引用一组均衡的优缺点至关重要。
12. Common Exam Question Types and Tips | 常见考试题型与提示
IB and OCR OOP questions often fall into these patterns:
- Code tracing: You are given a class definition and a fragment that creates objects and calls methods. Predict the output, paying attention to constructor calls, overridden methods, and static vs instance context.
- Code completion: A partially written class is provided; you fill in missing constructor, getter/setter, or method body according to comments or specifications.
- UML interpretation/construction: Draw or annotate a UML class diagram from a scenario, ensuring correct arrows and multiplicities.
- Scenario‑based design: Propose a class hierarchy, decide between abstract class and interface, and justify your design with reference to encapsulation, inheritance, and polymorphism.
- Evaluation: Critically analyse an existing design or discuss OOP concepts in the context of real‑world software development, mentioning SOLID or other principles.
IB 和 OCR 的面向对象题目通常包含以下几种模式:
- 代码追踪:给出一个类定义及创建对象和调用方法的片段,预测输出,注意构造函数调用、重写方法以及静态与实例上下文。
- 代码补全:提供一个部分完成的类,根据注释或规范填写缺失的构造函数、getter/setter 或方法体。
- UML 解读/构建:根据场景绘制或注释 UML 类图,确保正确的箭头和多重性。
- 基于场景的设计:提出类层次结构,在抽象类和接口之间做出选择,并引用封装、继承和多态来证明设计的合理性。
- 评估:批判性地分析现有设计或在实际软件开发背景下讨论面向对象概念,提及 SOLID 或其他原则。
Key tips: Always initialise fields in constructors. Keep access modifiers appropriate (private fields, public methods unless otherwise stated). When writing inheritance, ensure the super call is correctly placed. Practice past papers with mark schemes to understand the level of detail examiners expect.
关键提示:务必在构造函数中初始化字段。保持适当的访问修饰符(字段 private,方法 public,除非另有要求)。编写继承时,确保 super 调用放置正确。利用评分方案练习往年真题,了解考官期望的详细程度。
Published by TutorHao | Computer Science Revision Series | aleveler.com
更多咨询请联系16621398022(同微信)

或截图后用「扫一扫 → 相册」选择本图