📚 Object-Oriented Programming Principles | 面向对象编程原则
Object-oriented programming (OOP) is a programming paradigm that organises code around ‘objects’ rather than functions and logic. An object encapsulates data and the operations that can be performed on that data, promoting modularity, reusability and maintainability. In the Edexcel A-Level Computer Science specification, understanding OOP concepts such as classes, objects, inheritance, polymorphism and encapsulation is fundamental to mastering modern software design. This article explores the core principles, their practical implementation in pseudocode, and the advantages they bring to large‑scale system development.
面向对象编程(OOP)是一种围绕“对象”而非函数和逻辑来组织代码的编程范式。一个对象将数据及可对该数据执行的操作封装在一起,从而提升了模块化、可重用性和可维护性。在 Edexcel A-Level 计算机科学大纲中,理解类、对象、继承、多态和封装等面向对象概念是掌握现代软件设计的基础。本文探讨这些核心原则、它们在伪代码中的实际实现,以及它们为大规模系统开发带来的优势。
1. Programming Paradigms and the Need for OOP | 编程范式与面向对象编程的必要性
Before the widespread adoption of OOP, procedural programming dominated software development. In procedural programming, a program is a sequence of instructions operating on shared data, often leading to tight coupling and difficulties in managing large codebases. OOP addresses these limitations by grouping related data and behaviours into self‑contained units called objects, enabling developers to model real‑world entities more naturally.
在面向对象编程广泛采用之前,过程式编程主导了软件开发。在过程式编程中,程序是对共享数据进行操作的一系列指令,这往往导致高度耦合,并且难以管理大型代码库。面向对象编程通过将相关数据和行为组合到称为对象的独立单元中,解决了这些局限,使开发人员能够更自然地模拟现实世界实体。
Think of a university management system. Using a procedural approach, student records might be scattered across arrays and procedures. With OOP, a Student object holds its own name, ID and grades, and provides methods to enrol in courses or calculate averages. This mirrors how we perceive the world—as interacting entities with properties and capabilities.
设想一个大学管理系统。使用过程式方法时,学生记录可能分散在多个数组和过程中。而使用面向对象方法时,一个 Student 对象包含自己的姓名、学号和成绩,并提供注册课程或计算平均分的方法。这反映了我们对世界的感知方式——具有属性和能力的交互实体。
The shift from procedural to object‑oriented thinking encourages abstraction at a higher level. Instead of focusing on the step‑by‑step flow of control, the programmer first identifies the key entities, their responsibilities and how they collaborate. This design approach, often supported by UML class diagrams, greatly simplifies both initial development and later maintenance.
从过程式思维到面向对象思维的转变鼓励了更高层次的抽象。程序员不再专注于一步一步的控制流,而是首先识别关键实体、它们的职责以及它们如何协作。这种设计方法通常由 UML 类图支持,极大地简化了初始开发和后续维护。
2. Classes and Objects: Blueprints and Instances | 类与对象:蓝图与实例
A class is a blueprint or template that defines the attributes (data) and methods (behaviours) that the objects created from it will possess. It does not allocate memory for data until an object is instantiated. An object is a specific instance of a class, holding its own copy of the attributes defined by the class. For example, a Car class might define attributes such as colour, make, and speed, and methods such as accelerate() and brake(). A red Toyota Camry with speed 0 would be one object of that class.
类是定义由其创建的对象将拥有的属性(数据)和方法(行为)的蓝图或模板。在对象实例化之前,它不会为数据分配内存。对象是类的具体实例,持有着该类定义的属性的自己的一份副本。例如,一个 Car 类可以定义属性如 colour、make 和 speed,以及方法如 accelerate() 和 brake()。一辆速度为 0 的红色丰田凯美瑞就是该类的一个对象。
In pseudocode terminology used in Edexcel examinations, a class is defined using the CLASS keyword, and an object is created using the NEW keyword. Attributes are typically declared as PRIVATE, and methods as PUBLIC, forming the basis of encapsulation which we will discuss shortly. Consider the following skeletal pseudocode:
在 Edexcel 考试使用的伪代码术语中,类用 CLASS 关键字定义,对象用 NEW 关键字创建。属性通常声明为 PRIVATE,方法声明为 PUBLIC,这构成了我们稍后将讨论的封装的基础。请看以下骨架伪代码:
CLASS Car
PRIVATE colour: STRING
PRIVATE speed: INTEGER
PUBLIC PROCEDURE accelerate(increment: INTEGER)
self.speed ← self.speed + increment
END PROCEDURE
END CLASS
myCar ← NEW Car
Understanding the distinction between a class and an object is crucial: the class exists at compile time as a description, while objects exist at runtime as memory‑resident entities that interact with one another.
理解类与对象之间的区别至关重要:类在编译时作为描述存在,而对象在运行时作为驻留在内存中并相互交互的实体存在。
3. Attributes, Methods and the Self Reference | 属性、方法和自身引用
Attributes (also called fields or properties) store the state of an object. In OOP, it is best practice to keep attributes private so that they can only be accessed or modified through the object’s own methods. Methods define the behaviour of the object and are typically public, providing a controlled interface to the outside world. The special keyword self (or this in some languages) refers to the current object instance, allowing a method to access the attributes of the specific object on which it was called.
属性(也称为字段或特性)存储对象的状态。在面向对象编程中,最佳实践是保持属性为私有,以便它们只能通过对象自身的方法进行访问或修改。方法定义了对象的行为,通常是公有的,为外界提供受控的接口。特殊关键字 self(在某些语言中为 this)指向当前对象实例,使方法能够访问调用它的特定对象的属性。
For instance, a BankAccount class might have a private attribute balance and a public method deposit(amount). The deposit procedure would use self.balance to update the balance of the particular account object. Without self, the method would not know which object’s balance to modify. This mechanism underpins the ability to have many objects of the same class, each maintaining its own independent state.
例如,一个 BankAccount 类可能有一个私有属性 balance 和一个公有方法 deposit(amount)。deposit 过程将使用 self.balance 来更新特定账户对象的余额。没有 self,方法就不知道要修改哪个对象的余额。这一机制支撑了拥有同一类的多个对象的能力,每个对象都保持自己独立的状态。
In Edexcel pseudocode, attributes are declared in the class body and are accessed with dot notation, e.g. myAccount.balance. However, if balance is PRIVATE, external code cannot use this notation; it must call the public method instead. This enforcement of access control is a cornerstone of robust design.
在 Edexcel 伪代码中,属性在类体中声明,并使用点标记法访问,例如 myAccount.balance。但是,如果 balance 是 PRIVATE,外部代码就不能使用这种标记法;它必须转而调用公有方法。这种访问控制的强制实施是稳健设计的基石。
4. Encapsulation: Protecting Internal State | 封装:保护内部状态
Encapsulation is the principle of bundling data and the methods that operate on that data within a single unit (the class) and restricting direct access to some of the object’s components. This is achieved by marking attributes as private and providing public accessor (get) and mutator (set) methods where appropriate. Encapsulation hides the internal representation from the outside, exposing only what is necessary, which reduces complexity and prevents unintended interference.
封装是将数据及操作这些数据的方法绑定在单个单元(类)中,并限制对对象某些组件的直接访问的原则。这通过将属性标记为私有并在适当的地方提供公有的访问器(get)和修改器(set)方法来实现。封装将内部表示隐藏起来,只暴露必要的内容,从而降低了复杂性并防止了意外的干扰。
Consider a Temperature class with a private celsius attribute. A setCelsius(value) mutator can enforce validation, ensuring the value is above absolute zero, and a getFahrenheit() accessor can return the equivalent Fahrenheit value without storing it. The client code does not need to know whether the temperature is stored in Celsius or Kelvin—it simply uses the interface. This insulation makes the system easier to change: the internal data representation can be altered without affecting dependent code.
考虑一个带有私有 celsius 属性的 Temperature 类。setCelsius(value) 修改器可以执行验证,确保值高于绝对零度,而 getFahrenheit() 访问器可以返回等效的华氏温度值而不存储它。客户端代码无需知道温度是以摄氏度还是开尔文存储的——它只需使用接口。这种隔离使系统更易于更改:内部数据表示可以在不影响依赖代码的情况下进行更改。
Encapsulation also helps maintain invariants. If a class’s balance must never be negative, the mutator can reject invalid values; direct attribute access would allow any code to set it to a nonsensical state. Together with well‑defined method contracts, encapsulation leads to more reliable and maintainable software.
封装还有助于维护不变量。如果一个类的余额永远不能为负,修改器可以拒绝无效值;而直接访问属性则允许任何代码将其设置为荒谬的状态。与方法合约定好一起,封装实现了更可靠、更可维护的软件。
5. Inheritance: Building Hierarchies | 继承:构建层次结构
Inheritance allows a new class (subclass or derived class) to absorb the attributes and methods of an existing class (superclass or base class). The subclass can then extend or override the inherited behaviour to suit its specific needs. This promotes code reuse and establishes a natural ‘is‑a’ relationship. For example, a Dog class might inherit from an Animal class, gaining attributes such as species and methods such as eat(), while adding its own bark() method.
继承允许一个新类(子类或派生类)吸收一个现有类(超类或基类)的属性和方法。然后,子类可以扩展或覆盖继承的行为以满足其具体需求。这促进了代码重用,并建立了自然的“是”关系。例如,一个 Dog 类可以继承自 Animal 类,获得 species 等属性和 eat() 等方法,同时添加自己的 bark() 方法。
In Edexcel pseudocode, inheritance is expressed with the INHERITS keyword. A superclass constructor can be invoked using the SUPER keyword, ensuring that the base class is properly initialised. Suppose we have an Employee superclass and a Manager subclass that adds a teamSize attribute. The Manager’s constructor calls SUPER to initialise the inherited name and salary, then sets its own unique attribute. This avoids duplication of the common employee code.
在 Edexcel 伪代码中,继承用 INHERITS 关键字表示。可以使用 SUPER 关键字调用超类构造函数,以确保基类被正确初始化。假设我们有一个 Employee 超类和一个添加了 teamSize 属性的 Manager 子类。Manager 的构造函数调用 SUPER 来初始化继承的 name 和 salary,然后设置自己特有的属性。这避免了公共员工代码的重复。
Inheritance can be multilevel, forming chains such as Animal → Mammal → Dog. However, deep inheritance hierarchies can become brittle; modern design often favours composition over inheritance for flexibility. Still, for A‑Level studies, understanding simple inheritance and method overriding is essential, as questions frequently ask you to interpret or extend a given class diagram or pseudocode snippet.
继承可以是多层次的,形成诸如 Animal → Mammal → Dog 的链条。然而,深度继承层次结构可能变得脆弱;现代设计通常更倾向于使用组合而非继承以获得灵活性。尽管如此,对于 A-Level 学习而言,理解简单的继承和方法覆盖至关重要,因为考题经常要求你解释或扩展给定的类图或伪代码片段。
6. Polymorphism: One Interface, Many Forms | 多态:一个接口,多种形态
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. Polymorphism enables a single line of code to invoke different methods depending on the runtime type of the object, making systems more extensible.
多态,意为“多种形态”,允许将不同类的对象视为公共超类的对象来处理。最常见的形式是方法覆盖,即子类提供了其超类中已定义的方法的特定实现。多态使得一行代码能够根据对象的运行时类型调用不同的方法,从而使系统更具可扩展性。
Imagine a drawing application with a base class Shape and subclasses Circle, Rectangle and Triangle. Each subclass overrides a draw() method. An array of Shape references can hold objects of any subclass, and iterating over it calling draw() will invoke the correct version for each shape. The calling code does not need conditional statements to distinguish between types; this is known as dynamic binding or late binding.
想象一个绘图应用程序,它有一个基类 Shape 以及子类 Circle、Rectangle 和 Triangle。每个子类都覆盖了 draw() 方法。一个 Shape 引用数组可以保存任何子类的对象,遍历该数组并调用 draw() 将为每个形状调用正确的版本。调用代码不需要条件语句来区分类型;这被称为动态绑定或后期绑定。
Polymorphism is also supported through interfaces (or abstract classes) which define a set of method signatures that any implementing class must provide. This allows completely unrelated classes to be used interchangeably as long as they adhere to the same contract. For A-Level, you should be able to recognise polymorphic behaviour in pseudocode and explain why it reduces coupling and simplifies maintenance.
多态也通过接口(或抽象类)得到支持,接口定义了一组任何实现类都必须提供的方法签名。这使得完全无关的类只要遵循相同的契约就可以互换使用。对于 A-Level,你应该能够识别伪代码中的多态行为,并解释它为何能减少耦合并简化维护。
7. Abstract Classes and Interfaces | 抽象类与接口
An abstract class is a class that cannot be instantiated directly; it exists to be inherited by subclasses that provide concrete implementations of its abstract methods. An abstract method has a signature but no body. Abstract classes are useful when you want to provide some common functionality (e.g., a default move() method) while forcing subclasses to implement others (e.g., makeSound()). In contrast, an interface is a purely abstract contract that specifies a set of methods with no implementation at all; a class can implement multiple interfaces, achieving a form of multiple inheritance of behaviour.
抽象类是无法直接实例化的类;它的存在是为了被子类继承,由子类提供其抽象方法的具体实现。抽象方法有签名但没有主体。当你想提供一些通用功能(例如默认的 move() 方法)的同时强制子类实现其他方法(例如 makeSound())时,抽象类非常有用。相比之下,接口是一个纯抽象的契约,它指定了一组根本没有实现的方法;一个类可以实现多个接口,从而实现一种行为上的多重继承。
In Edexcel pseudocode, abstract classes can be indicated with the ABSTRACT keyword before CLASS. An abstract method is similarly marked. For example, an abstract Vehicle class might declare ABSTRACT PROCEDURE calculateRange() to be implemented by ElectricCar and PetrolCar subclasses. An interface can be denoted with the INTERFACE keyword, and classes use IMPLEMENTS to fulfil the interface contract. Such constructs enforce design discipline and enable polymorphic collections.
在 Edexcel 伪代码中,抽象类可以用 CLASS 前的 ABSTRACT 关键字来指示。抽象方法也类似地标记。例如,一个抽象的 Vehicle 类可以声明 ABSTRACT PROCEDURE calculateRange() 让 ElectricCar 和 PetrolCar 子类去实现。接口可以用 INTERFACE 关键字表示,类使用 IMPLEMENTS 来履行接口契约。这些结构强制执行设计规范,并支持多态集合。
Choosing between abstract classes and interfaces depends on whether shared state (attributes) needs to be inherited. Abstract classes can hold attributes and provide concrete methods; interfaces cannot hold state and (in many languages) only declare method signatures. Understanding these differences is a common exam requirement, especially when evaluating the suitability of design models.
在抽象类和接口之间进行选择取决于是否需要继承共享状态(属性)。抽象类可以持有属性并提供具体方法;接口不能持有状态,并且(在许多语言中)只能声明方法签名。理解这些差异是一个常见的考试要求,尤其是在评估设计模型的适用性时。
8. Object Relationships: Association, Aggregation and Composition | 对象关系:关联、聚合与组合
Real‑world systems are composed of objects that are linked through various relationships. Association is a general ‘uses‑a’ relationship where objects interact but do not own each other. Aggregation is a specialised form of association representing a ‘has‑a’ relationship where a whole is made up of parts, but the parts can exist independently of the whole. Composition is a stronger form of aggregation where the parts have a lifecycle tied to the whole; if the whole is destroyed, its composed parts are also destroyed.
现实世界的系统由通过各种关系连接的对象组成。关联是一种通用的“使用”关系,对象之间交互但不相互拥有。聚合是关联的一种特殊形式,表示“拥有”关系,整体由部分组成,但部分可以独立于整体存在。组合是聚合的一种更强形式,其中部分的生命周期与整体绑定;如果整体被销毁,其构成部分也会被销毁。
For example, a Library and Member classes share an association because a member borrows books but exists independently. A Car and its Engine are typically related by composition because the engine is created when the car is built and ceases to be useful if the car is scrapped. A University and its Departments might be modelled as aggregation, as a department could theoretically be transferred to another institution.
例如,Library 和 Member 类共享关联关系,因为成员借书但独立存在。Car 和它的 Engine 通常通过组合相关,因为引擎在汽车制造时被创建,并且如果汽车报废就不再有用。University 和其 Department 可以被建模为聚合,因为理论上一个院系可以被转移到另一个机构。
In pseudocode and class diagrams, these relationships are shown by lines with different notation: a simple line for association, a hollow diamond for aggregation, and a filled diamond for composition. For the exam, you may be asked to identify and justify the relationship type from a scenario, so practising with real‑world analogies is highly beneficial.
在伪代码和类图中,这些关系通过带有不同符号的线条表示:简单线条表示关联,空心菱形表示聚合,实心菱形表示组合。对于考试,你可能会被要求从场景中识别并证明关系类型,因此用现实世界的类比进行练习非常有益。
9. Advantages of Object-Oriented Programming | 面向对象编程的优势
OOP offers several advantages that make it the dominant paradigm for large‑scale software. Reusability is greatly enhanced through inheritance and composition: well‑designed classes can be reused across projects, reducing development time. Modularity is achieved because each class is a self‑contained unit; changes to one class often do not necessitate changes to others, as long as the public interface remains stable.
面向对象编程提供了几个优势,使其成为大规模软件的主导范式。通过继承和组合,可重用性得到了极大的增强:设计良好的类可以在项目之间重用,从而减少开发时间。模块化得以实现,因为每个类都是一个独立的单元;只要公有接口保持稳定,对一个类的更改通常不需要更改其他类。
Maintainability and extensibility are natural by‑products of encapsulation and polymorphism. When new requirements arise, a developer can add new subclasses or implement interfaces without modifying existing, tested code—adhering to the open‑closed principle. Moreover, OOP maps well to the human cognitive model, making it easier for teams to analyse, design and discuss complex systems using shared terminology like classes, objects and collaboration.
可维护性和可扩展性是封装和多态的自然副产品。当出现新需求时,开发人员可以添加新的子类或实现接口,而无需修改现有的、经过测试的代码——这遵循了开闭原则。此外,面向对象编程很好地映射到人类的认知模型,使团队更容易使用类、对象和协作等共享术语来分析、设计和讨论复杂系统。
However, OOP is not without drawbacks. It can introduce a steeper learning curve and, if poorly designed, lead to excessively deep inheritance trees that complicate debugging. Nonetheless, for the scope of A‑Level Computer Science, a solid grasp of OOP principles lays the groundwork for understanding advanced topics in software engineering and design patterns.
然而,面向对象编程也并非没有缺点。它可能带来更陡峭的学习曲线,而且如果设计不当,会导致过深的继承树,从而使调试复杂化。尽管如此,在 A-Level 计算机科学的范围内,扎实掌握面向对象原则为理解软件工程和设计模式中的高级主题奠定了基础。
10. OOP in Pseudocode: Exam-Style Application | 伪代码中的面向对象:考试风格应用
Edexcel examination papers frequently present a scenario and ask you to write pseudocode that demonstrates OOP features. A typical question might provide a partial class diagram for a vehicle hire system and ask you to write a class definition, including a constructor, getter methods and a method that calculates hire cost. You may also be asked to explain how inheritance could reduce code duplication if a Van class were added.
Edexcel 试卷经常会提供一个场景,并要求你编写展示面向对象特性的伪代码。一个典型的问题可能会给出车辆租赁系统的部分类图,要求你编写一个类定义,包括构造函数、获取方法和计算租赁费用的方法。你还可能被要求解释如果添加一个 Van 类,继承如何能够减少代码重复。
When constructing such answers, pay attention to the pseudocode syntax, including correct use of CLASS, PRIVATE, PUBLIC, NEW, INHERITS, SUPER, and ABSTRACT. Always initialise attributes in the constructor, use self where appropriate, and ensure access control is respected. For instance, if the specification says ‘name can only be read, not modified externally’, provide a getName() accessor but no setName() mutator.
在构建这类答案时,请注意伪代码语法,包括正确使用 CLASS、PRIVATE、PUBLIC、NEW、INHERITS、SUPER 和 ABSTRACT。始终在构造函数中初始化属性,在适当的地方使用 self,并确保访问控制得到遵守。例如,如果规格说明“name 只能被读取,不能被外部修改”,则提供 getName() 访问器,但不提供 setName() 修改器。
Practice writing a complete class hierarchy from a narrative description. For example: ‘A school has teachers and students. All persons have names and IDs. Teachers have a subject specialism; students have a year group and a method to calculate exam average. Model this using OOP, with appropriate inheritance and encapsulation.’ This mirrors the extended response questions and builds confidence in applying theory.
练习根据叙述性描述编写完整的类层次结构。例如:“一所学校有教师和学生。所有人都有姓名和 ID。教师有一个学科专长;学生有一个年级组和一个计算考试平均分的方法。使用面向对象方法对此建模,包含适当的继承和封装。”这模仿了扩展回答题目,并建立了应用理论的信心。
Remember: examiners look for correct use of terminology, proper access modifiers, and logical structure. Even small mistakes such as omitting the NEW keyword or forgetting to declare an attribute private can lose marks. Regularly testing your pseudocode by tracing method calls on paper will sharpen your precision.
请记住:考官看重术语的正确使用、恰当的访问修饰符以及逻辑结构。即使是遗漏 NEW 关键字或忘记将属性声明为 private 这样的小错误也可能失分。通过纸上追踪方法调用来定期测试你的伪代码将提高你的精确度。
Published by TutorHao | Programming Revision Series | aleveler.com
更多咨询请联系16621398022(同微信)
屏轩国际教育cambridge primary/secondary checkpoint, cat4, ukiset,ukcat,igcse,alevel,PAT,STEP,MAT, ibdp,ap,ssat,sat,sat2课程辅导,国外大学本科硕士研究生博士课程论文辅导