📚 Object-Oriented Programming: Key Concepts for IB and AQA Computer Science | 面向对象编程考点精讲(IB与AQA计算机)
Object-oriented programming (OOP) is a fundamental paradigm in computer science, central to both the IB Diploma Computer Science syllabus and the AQA A-level Computer Science specification. Mastering OOP concepts such as encapsulation, inheritance, and polymorphism is essential for success in Paper 2 (IB) and the programming project, as well as the AQA theory and practical exams. This article breaks down each key topic with clear explanations and examples, ensuring you are thoroughly prepared.
面向对象编程(OOP)是计算机科学中的核心范式,在IB文凭计算机科学课程和AQA A-level计算机科学规范中都占据重要地位。掌握封装、继承和多态等OOP概念,对于IB Paper 2和编程项目,以及AQA的理论与实践考试至关重要。本文将逐一解析每个关键考点,配以清晰的解释和示例,帮助你全面备考。
1. Classes and Objects | 类与对象
A class is a blueprint or template that defines the attributes (data) and methods (behaviour) common to all objects of a certain kind. An object is an instance of a class, representing a specific entity with actual values for the attributes.
类是定义某类对象共同属性(数据)和方法(行为)的蓝图或模板。对象是类的实例,代表一个具体的实体,其属性具有实际值。
For example, a ‘Car’ class may have attributes like colour, model, and speed, and methods such as accelerate() and brake(). An object of Car could be ‘myCar’ with colour ‘red’ and model ‘Tesla’. The same class can produce many distinct objects, each holding its own independent state.
例如,一个“Car”类可能具有颜色、型号和速度等属性,以及accelerate()和brake()等方法。Car的一个对象可以是“myCar”,颜色为“红色”,型号为“Tesla”。同一个类可以创建多个不同的对象,每个对象都拥有自己独立的状态。
In IB and AQA pseudocode, you create an object by calling the class constructor, e.g., myCar = new Car('red', 'Tesla'). Understanding the distinction between a class (a logical structure) and an object (a physical entity in memory) is a frequent exam question and vital for designing solutions.
在IB和AQA的伪代码中,通过调用类的构造函数来创建对象,例如 myCar = new Car('red', 'Tesla')。理解类(逻辑结构)与对象(内存中的物理实体)之间的区别是常见的考题,对设计解决方案也至关重要。
2. Encapsulation and Access Modifiers | 封装与访问修饰符
Encapsulation is the practice of bundling data (attributes) with the methods that operate on that data, and restricting direct access to an object’s internal state. It is achieved through access modifiers: private, public, and protected. Private attributes can only be accessed within the same class, while public methods provide a controlled interface to the outside world.
封装是将数据(属性)和操作这些数据的方法捆绑在一起,并限制对对象内部状态的直接访问。它通过访问修饰符实现:private、public 和 protected。私有属性只能在同一个类中访问,而公共方法则为外界提供受控的接口。
By making attributes private and exposing public getter and setter methods, you enforce validation and maintain integrity. For example, a BankAccount class might have a private balance attribute and a public deposit(amount) method that checks for positive amounts before modifying the balance.
通过将属性设为私有并暴露公共的 getter 和 setter 方法,你可以强制进行验证并维护数据的完整性。例如,BankAccount 类可以包含私有属性 balance,以及一个公共方法 deposit(amount),该方法在修改余额之前会检查金额是否为正数。
The following table summarises the typical visibility of access modifiers used in Java, C++, and similar languages examined by IB and AQA.
下表总结了IB和AQA考试中可能涉及的Java、C++等语言中访问修饰符的典型可见性。
| Modifier | Same Class | Subclass | World |
|---|---|---|---|
| private | Yes | No | No |
| public | Yes | Yes | Yes |
| protected | Yes | Yes | No |
3. Constructors and Destructors | 构造函数与析构函数
A constructor is a special method automatically invoked when an object is instantiated. It typically initialises the object’s attributes and ensures the object starts in a valid state. In many languages, the constructor has the same name as the class and no return type.
构造函数是一种特殊方法,在对象实例化时自动调用。它通常用于初始化对象的属性,并确保对象始于有效状态。在许多语言中,构造函数与类同名且无返回类型。
Multiple constructors can be defined through overloading, offering different ways to create objects with varying amounts of initial data. For IB and AQA, you need to recognise default constructors (provided automatically if none defined) and parameterised constructors.
可以通过重载定义多个构造函数,以不同数量和类型的初始数据来创建对象。在IB和AQA考试中,你需要能识别默认构造函数(如果没有定义则自动提供)和带参数的构造函数。
Destructors (or finalisers) are used in some languages to perform cleanup before an object is destroyed. While not explicitly examined in all IB pseudocode, knowing the concept helps understand resource management. For example, in C++ a destructor is written as ~ClassName().
析构函数(或终结器)在某些语言中用于在对象销毁前执行清理工作。虽然并非所有IB伪代码都会明确考查,但理解这一概念有助于掌握资源管理。例如,在C++中析构函数写作 ~ClassName()。
4. Inheritance | 继承
Inheritance allows a new class (subclass or derived class) to acquire the properties and methods of an existing class (superclass or base class). It promotes code reusability and establishes a hierarchical relationship. The subclass can add its own unique attributes and methods, or override inherited methods to provide specialised behaviour.
继承允许新类(子类或派生类)获取现有类(超类或基类)的属性和方法。它提升了代码的可重用性并建立了层次关系。子类可以添加自己独有的属性和方法,也可以覆盖继承的方法以提供专门的行为。
In IB Java/Python examples and AQA pseudocode, the keyword extends (Java) or parentheses with the parent class name (Python) denotes inheritance. For instance, a ‘Dog’ class might inherit from an ‘Animal’ class, gaining attributes like age and methods like eat(), while adding a bark() method.
在IB的Java/Python示例和AQA伪代码中,使用关键字 extends(Java)或在括号中写出父类名称(Python)表示继承。例如,“Dog”类可以继承自“Animal”类,获得age属性和eat()方法,并添加bark()方法。
You must be able to draw and interpret inheritance diagrams where an arrow points from the subclass to the superclass. A common exam pitfall is forgetting that private members of the superclass are not directly accessible in the subclass, though they are inherited.
你必须能够绘制和解读继承关系图,其中箭头从子类指向超类。一个常见的考试陷阱是忘记超类的私有成员在子类中无法直接访问,尽管它们确实被继承了。
5. Polymorphism | 多态
Polymorphism, meaning “many forms”, allows objects of different classes to be treated as objects of a common superclass. The most common form is method overriding, where a subclass provides a specific implementation of a method that is already defined in its superclass.
多态(意为“多种形态”)允许将不同类的对象当作共同超类的对象来处理。最常见的形式是方法重写,即子类为超类中已定义的方法提供具体的实现。
For example, a superclass ‘Shape’ may declare a method draw(). Subclasses ‘Circle’ and ‘Rectangle’ each override draw() to render themselves appropriately. A reference variable of type Shape can point to any subclass object, and calling draw() will execute the correct overridden method based on the actual object type — this is dynamic binding.
例如,超类“Shape”可以声明方法draw()。子类“Circle”和“Rectangle”各自重写draw()以适当地渲染自己。Shape类型的引用变量可以指向任何子类对象,调用draw()时会根据实际对象类型执行正确的重写方法——这就是动态绑定。
IB and AQA questions often ask you to identify scenarios where polymorphism is used, explain its advantages (flexibility, extensibility), and implement simple polymorphic behaviour using abstract classes or interfaces.
IB和AQA的试题经常要求你识别使用多态的场景,解释其优点(灵活性、可扩展性),并使用抽象类或接口实现简单的多态行为。
6. Abstract Classes and Interfaces | 抽象类与接口
An abstract class is a class that cannot be instantiated on its own and may contain abstract methods (methods without a body) that must be implemented by concrete subclasses. It can have both abstract and concrete methods, as well as instance variables. An interface is a fully abstract contract that defines a set of method signatures with no implementation; classes implement the interface and must provide bodies for all its methods.
抽象类是不能被自身实例化的类,它可以包含抽象方法(没有方法体的方法),这些方法必须由具体子类来实现。抽象类可以同时拥有抽象方法和具体方法,以及实例变量。接口是一种完全抽象的契约,定义了一组只有签名没有实现的方法;类实现该接口,且必须为其所有方法提供方法体。
In Java, a class can implement multiple interfaces but can extend only one abstract class. This distinction is frequently tested. For IB Computer Science, both abstract classes and interfaces are essential for designing scalable solutions, while AQA often focuses on their role in achieving polymorphism.
在Java中,一个类可以实现多个接口,但只能继承一个抽象类。这一区别常被考查。对IB计算机科学而言,抽象类和接口对于设计可扩展的解决方案至关重要,而AQA往往关注它们在实现多态中的作用。
Recognise how to declare them: in Java, abstract class Vehicle and interface Movable; in IB pseudocode, they are often written with the keywords ABSTRACT CLASS and INTERFACE. You may be required to complete a class definition that implements a given interface.
要能识别它们的声明方式:在Java中,abstract class Vehicle 和 interface Movable;在IB伪代码中,常使用关键字 ABSTRACT CLASS 和 INTERFACE。你可能需要补全一个实现给定接口的类定义。
7. Association, Aggregation, and Composition | 关联、聚合与组合
Beyond inheritance, objects can be related through association, which represents a “uses-a” or “knows-a” relationship. Aggregation and composition are specialised forms of association that depict whole-part relationships. Composition implies a strong ownership where the part cannot exist independently of the whole; aggregation implies a weaker relationship where the part can exist independently.
除了继承,对象之间还可以通过关联建立关系,关联表示“使用”或“知道”的关系。聚合和组合是关联的特殊形式,表示整体与部分的关系。组合意味着强所有权,部分不能脱离整体独立存在;聚合则表示较弱的关系,部分可以独立存在。
For example, a ‘University’ object might contain many ‘Department’ objects — if the university is destroyed, the departments logically cease to exist, implying composition. A ‘Library’ might have many ‘Book’ objects, but a book can exist without the library, representing aggregation.
例如,“University”对象可能包含多个“Department”对象——如果大学被销毁,这些院系在逻辑上也就不复存在,这暗示着组合关系。“Library”可能拥有许多“Book”对象,但一本书可以脱离图书馆存在,这代表聚合关系。
In IB and AQA, you need to identify these relationships from scenario descriptions and represent them correctly in UML diagrams, using appropriate line styles (hollow diamond for aggregation, filled diamond for composition).
在IB和AQA的考试中,你需要从场景描述中识别这些关系,并在UML图中正确表示它们,使用恰当的线条样式(空心菱形表示聚合,实心菱形表示组合)。
8. UML Class Diagrams | UML 类图
Unified Modelling Language (UML) class diagrams are the standard way to visually represent OOP designs. A class is shown as a rectangle divided into three compartments: class name, attributes, and methods. Attributes and methods are prefixed with visibility markers: ‘+’ for public, ‘-‘ for private, and ‘#’ for protected.
统一建模语言(UML)类图是可视化表示OOP设计的标准方式。类显示为分为三个部分的矩形:类名、属性和方法。属性和方法前带有可见性标记:’+’ 表示公共,’-‘ 表示私有,’#’ 表示受保护。
Relationships are depicted by lines connecting classes. Inheritance uses a triangular hollow arrow pointing to the superclass. Association is a simple solid line, optionally with multiplicity (e.g., 1..* or 0..1). Aggregation uses a hollow diamond at the whole end, composition a filled diamond.
关系通过连接类的线条来描绘。继承使用指向超类的空心三角箭头。关联是一条简单的实线,可附带多重性(例如 1..* 或 0..1)。聚合在整体端使用空心菱形,组合使用实心菱形。
Both IB Paper 2 and AQA exams frequently include tasks such as drawing a UML diagram from a given specification, interpreting existing diagrams, or adding missing relationships and multiplicities. Practice constructing diagrams for simple systems like a school management system or a library.
IB Paper 2 和 AQA 考试经常包含以下任务:根据给定的规格说明绘制UML图、解读现有图表,或补充缺失的关系和多重性。应多加练习为简单系统(如学校管理系统或图书馆)构造类图。
9. Object-Oriented Design Principles | 面向对象设计原则
While you are not expected to memorise all SOLID principles in depth, IB and AQA syllabi reward understanding of good design. Keywords include cohesion (how closely related the responsibilities of a single class are) and coupling (the degree of interdependence between classes). High cohesion and loose coupling are desirable.
虽然不要求深入记忆所有SOLID原则,但IB和AQA大纲鼓励对良好设计的理解。相关关键词包括内聚(单个类的职责相关程度)和耦合(类之间的相互依赖程度)。高内聚、低耦合是理想状态。
Another vital concept is programming to an interface, not an implementation. This means relying on abstract interfaces or superclasses rather than concrete classes, which enhances flexibility and makes future changes easier. This connects directly to polymorphism and is often tested through scenario-based questions.
另一个重要概念是针对接口编程,而非针对实现编程。这意味着依赖抽象接口或超类而不是具体类,从而增强灵活性并使后续修改更加容易。这直接关联到多态,并常常通过基于场景的问题来考查。
You should also understand the idea of code reuse through inheritance and composition, and be able to evaluate when to use inheritance (“is-a”) versus composition (“has-a”). For instance, a Car “is-a” Vehicle (inheritance), but a Car “has-a” Engine (composition).
你还应理解通过继承和组合实现代码重用的思想,并能评估何时使用继承(“is-a”关系)与组合(“has-a”关系)。例如,汽车“是”交通工具(继承),但汽车“有”引擎(组合)。
10. Exception Handling and File I/O in an OOP Context | OOP背景下的异常处理与文件I/O
IB programming projects and AQA practical tasks often require robust OOP applications that handle errors using exceptions. Rather than crashing, your objects should throw exceptions when invalid data is provided, and client code should catch them using try-catch blocks. This keeps the program flow clean and separates error handling from normal logic.
IB编程项目和AQA实践任务通常要求健壮的OOP应用程序,能够使用异常来处理错误。当提供无效数据时,你的对象应抛出异常,而客户代码应使用try-catch块来捕获它们。这使程序流程保持清晰,并将错误处理与正常逻辑分离开来。
For instance, a method that sets a student’s age might throw an IllegalArgumentException if the age is negative. The calling code can catch that exception and prompt the user appropriately without the whole program terminating unexpectedly.
例如,设置学生年龄的方法若接收到负值,可抛出一个 IllegalArgumentException。调用代码可以捕获该异常并恰当地提示用户,而不会导致整个程序意外终止。
Working with files is another common OOP scenario. Classes such as FileReader and BufferedReader (Java) or their Python equivalents encapsulate file operations, and good OOP design ensures these resources are closed after use, even if an error occurs. IB pseudocode uses OPENFILE and READ, but you should think of file operations wrapped within objects.
文件操作是另一个常见的OOP场景。像 FileReader 和 BufferedReader(Java)等类或Python中对等的类封装了文件操作,而良好的OOP设计确保这些资源在使用后被关闭,即使发生错误也不例外。IB伪代码使用 OPENFILE 和 READ,但你应将文件操作视为封装在对象中。
Published by TutorHao | Computer Science Revision Series | aleveler.com
更多咨询请联系16621398022(同微信)
屏轩国际教育cambridge primary/secondary checkpoint, cat4, ukiset,ukcat,igcse,alevel,PAT,STEP,MAT, ibdp,ap,ssat,sat,sat2课程辅导,国外大学本科硕士研究生博士课程论文辅导