Object-Oriented Programming (OOP) Principles | 面向对象编程(OOP)原则

📚 Object-Oriented Programming (OOP) Principles | 面向对象编程(OOP)原则

Object-oriented programming is a paradigm that structures software around ‘objects’ rather than functions and logic. For Edexcel A-Level Computer Science, understanding OOP is essential for designing robust, reusable code. This article breaks down the core concepts, using Python-style pseudocode to illustrate how classes, encapsulation, inheritance, and polymorphism work in practice.

面向对象编程是一种围绕“对象”而非函数和逻辑来构建软件的范式。对于Edexcel A-Level 计算机科学课程而言,理解 OOP 是设计稳健、可重用代码的关键。本文通过类 Python 伪代码逐一解析核心概念,展示类、封装、继承和多态在实际中如何运作。

1. What Is Object-Oriented Programming? | 什么是面向对象编程?

OOP models real-world entities as objects that contain both data (attributes) and behaviour (methods). Unlike procedural programming, which separates data and functions, OOP bundles them together, making it easier to manage complexity in large systems.

OOP 将现实世界实体建模为同时包含数据(属性)和行为(方法)的对象。与将数据和函数分离的面向过程编程不同,OOP 将它们捆绑在一起,从而更容易管理大型系统中的复杂性。

A class serves as a blueprint, and an object is an instance of that class. For example, a ‘Car’ class might have attributes like colour and speed, and methods like accelerate() or brake().

类充当蓝图,对象是该类的实例。例如,“Car”类可能拥有 colour 和 speed 等属性,以及 accelerate() 或 brake() 等方法。


2. Classes and Objects: The Core Building Blocks | 类与对象:核心构建块

A class defines the structure and behaviours that its objects will have. In Edexcel pseudocode, you declare a class with the keyword CLASS, followed by its name. Attributes are typically private, as indicated by an underscore prefix in Python, or by using PRIVATE in the exam’s pseudocode.

类定义了其对象将拥有的结构和行为。在 Edexcel 伪代码中,使用关键字 CLASS 声明类,后跟类名。属性通常是私有的,在 Python 中以下划线前缀表示,或在考试伪代码中使用 PRIVATE 指示。

An object is instantiated using the class name followed by parentheses, optionally passing initial values to a constructor method. Each object has its own state, stored in instance variables.

对象通过类名后跟括号来实例化,可选择将初始值传递给构造方法。每个对象都有自己的状态,存储在实例变量中。

CLASS Car
PRIVATE colour : STRING
PRIVATE speed : INTEGER
PUBLIC PROCEDURE new(givenColour)
colour = givenColour
speed = 0
ENDPROCEDURE
ENDCLASS


3. Encapsulation: Protecting Data Integrity | 封装:保护数据完整性

Encapsulation is the principle of bundling data with the methods that operate on that data, and restricting direct access to some of an object’s components. This prevents unintended interference and misuse of internal state.

封装是指将数据与操作这些数据的方法捆绑在一起,并限制对对象某些组件的直接访问。这可以防止对内部状态的意外干扰和误用。

In practice, attributes are declared as private. To read or modify them, you provide public getter and setter methods. This adds a layer of validation and abstraction.

实际上,属性被声明为私有的。要读取或修改它们,你需提供公共的 getter 和 setter 方法。这增加了一层验证和抽象。

For example, instead of allowing car.speed = -10, a setSpeed method can enforce that speed must be non-negative. This makes the class more robust and maintainable.

例如,通过 setSpeed 方法可以强制要求速度不能为负数,而不是允许 car.speed = -10。这使类更加健壮且易于维护。


4. Inheritance: Reusing and Extending Code | 继承:代码重用与扩展

Inheritance allows a new class (subclass or derived class) to absorb the attributes and methods of an existing class (superclass or base class). This promotes code reuse and the creation of hierarchical relationships.

继承允许新类(子类或派生类)吸收现有类(超类或基类)的属性和方法。这促进了代码重用和层次关系的建立。

The subclass can add new attributes and methods, or override existing ones to provide specialised behaviour. In Edexcel pseudocode, inheritance is indicated with INHERITS.

子类可以添加新的属性和方法,或者重写现有方法以提供特定行为。在 Edexcel 伪代码中,继承用 INHERITS 表示。

Consider an ‘ElectricCar’ class that inherits from ‘Car’. It inherits colour and speed, but might override the accelerate() method to model different acceleration, and add a batteryLevel attribute.

考虑一个从 “Car” 继承的 “ElectricCar” 类。它继承了 colour 和 speed,但可能重写 accelerate() 方法以模拟不同的加速过程,并添加 batteryLevel 属性。

CLASS ElectricCar INHERITS Car
PRIVATE batteryLevel : INTEGER
PUBLIC PROCEDURE new(givenColour, initialBattery)
super.new(givenColour)
batteryLevel = initialBattery
ENDPROCEDURE
ENDCLASS


5. Polymorphism: One Interface, Multiple Behaviours | 多态:同一接口,多种行为

Polymorphism means ‘many forms’. It allows objects of different classes to be treated as objects of a common superclass, with the appropriate method being called based on the actual object type at run time.

多态意为“多种形态”。它允许将不同类的对象视为共同超类的对象,并在运行时根据实际对象类型调用相应的方法。

Overriding is a form of polymorphism where a subclass provides a specific implementation of a method already defined in its superclass. The method signature remains the same, but the behaviour differs.

重写是多态的一种形式,即子类提供对其超类中已定义方法的具体实现。方法签名保持不变,但行为不同。

For instance, a list of Car objects (some Car, some ElectricCar) can each respond to accelerate(). The correct version is executed without explicit conditional checks, making code more flexible.

例如,一个包含 Car 对象的列表(部分为 Car,部分为 ElectricCar)可以对每个对象调用 accelerate()。无需显式条件检查即可执行正确的版本,使代码更加灵活。


6. Constructors and Destructors | 构造方法与析构方法

A constructor is a special method automatically called when an object is instantiated. It usually sets the initial state of the object. In many languages, including the Edexcel pseudocode, it is conventionally named new().

构造方法是在对象实例化时自动调用的特殊方法。它通常用于设置对象的初始状态。在包括 Edexcel 伪代码在内的许多语言中,按惯例将其命名为 new()。

Constructors can be overloaded, but in the pseudocode used for the exam, usually a single parameterised constructor is defined. The keyword super can be used to call the constructor of the parent class from within a subclass constructor.

构造方法可以被重载,但在考试使用的伪代码中,通常只定义一个带参数的构造方法。关键字 super 可用于从子类构造方法中调用父类的构造方法。

Destructors are less commonly examined at A-Level but are used to clean up resources before an object is destroyed. In pseudocode, they might be represented as a finalise procedure.

析构方法在 A-Level 考试中较少考查,但用于在对象销毁前清理资源。在伪代码中,它们可能表示为 finalise 过程。


7. Abstract Classes and Interfaces | 抽象类与接口

An abstract class is a class that cannot be instantiated directly. It may contain abstract methods (methods without a body) that must be implemented by any concrete subclass. This enforces a contract for derived classes.

抽象类是无法直接实例化的类。它可能包含抽象方法(没有方法体的方法),任何具体子类都必须实现这些方法。这为派生类强制规定了一份契约。

Interfaces define a set of method signatures that implementing classes must provide, offering a form of multiple inheritance of behaviour without implementation. Edexcel pseudocode may use INTERFACE keyword.

接口定义了一组方法签名,实现接口的类必须提供这些方法,从而提供了一种行为上的多重继承形式而不涉及实现。Edexcel 伪代码可能使用 INTERFACE 关键字。

Understanding abstract classes helps in designing systems where certain steps are deferred to subclasses, allowing for flexible and extensible architectures.

理解抽象类有助于设计将某些步骤推迟到子类完成的系统,从而实现灵活且可扩展的架构。


8. Association, Aggregation, and Composition | 关联、聚合与组合

Objects can relate to one another through ‘has-a’ relationships. Association is a general connection between classes. Aggregation implies a whole-part relationship where the part can exist independently of the whole.

对象可以通过“has-a”关系相互关联。关联是类之间的一般连接。聚合意味着整体与部分的关系,其中部分可以独立于整体存在。

Composition is a stronger form of aggregation where the part cannot exist without the whole, and the whole is responsible for creating and destroying its parts. For example, a House has Rooms; if the House is demolished, the Rooms are destroyed too.

组合是更强的聚合形式,其中部分不能脱离整体存在,且整体负责其部分的创建和销毁。例如,一所房子拥有多个房间;如果房子被拆毁,房间也会一同消失。

In Edexcel questions, you may be asked to identify these relationships in UML class diagrams, showing multiplicity and direction of association.

在 Edexcel 问题中,你可能会被要求识别 UML 类图中的这些关系,并标明多重性和关联方向。


9. OOP and Event-Driven Programming | 面向对象编程与事件驱动编程

Modern applications often combine OOP with event-driven programming. Objects can generate events and other objects can register listeners to respond. This paradigm is common in graphical user interfaces (GUIs).

现代应用程序通常将 OOP 与事件驱动编程结合使用。对象可以生成事件,其他对象可以注册监听器进行响应。这种范式在图形用户界面(GUI)中很常见。

In an Edexcel context, understanding how OOP structures support event handling helps when designing solutions that respond to user clicks, key presses, or timer ticks.

在 Edexcel 情境中,理解 OOP 结构如何支持事件处理有助于设计响应用户点击、按键或计时器事件的解决方案。

Components like buttons, text fields, and sliders are modelled as objects with properties and event-handler methods, enabling modular, maintainable front-end code.

按钮、文本框和滑块等组件被建模为具有属性和事件处理方法的对象,从而实现模块化、可维护的前端代码。


10. Common OOP Misconceptions in the Exam | 考试中常见的 OOP 误解

Many students confuse class and object, using them interchangeably. A class is a template, while an object is a specific instance with its own data. Losing marks for misusing these terms is avoidable.

许多学生混淆了类和对象,将它们混用。类是模板,而对象是具有自身数据的特定实例。避免术语误用可以防止失分。

Another pitfall is forgetting to declare attributes as private. Edexcel mark schemes often reward encapsulation by ensuring direct access to data is prevented unless through defined methods.

另一个陷阱是忘记将属性声明为私有。Edexcel 评分方案通常奖励通过已定义方法间接访问数据,防止直接访问,以此实现封装。

When writing constructors in pseudocode, ensure you initialise all relevant attributes, including those inherited from the superclass. Failing to call super.new() often results in incomplete initialisation.

在伪代码中编写构造方法时,务必初始化所有相关属性,包括从超类继承的属性。忘记调用 super.new() 常常导致初始化不完整。


11. Practical Design Considerations | 实际设计考量

When designing an OOP solution, first identify the nouns in the problem statement as potential classes, and the verbs as potential methods. This noun-verb analysis technique aligns with Edexcel design exercises.

设计 OOP 解决方案时,首先将问题陈述中的名词识别为潜在的类,将动词识别为潜在的方法。这种名词-动词分析技术与 Edexcel 设计练习相一致。

Favour composition over inheritance where appropriate, because deep inheritance hierarchies can become brittle. Composition allows dynamic behaviour changes by assembling objects with different capabilities.

在适当情况下优先使用组合而非继承,因为深层次的继承层级可能会变得脆弱。组合允许通过组合不同功能的对象来动态改变行为。

Always keep cohesion high and coupling low. Cohesive classes have a single, well-defined purpose; low coupling means minimal dependencies between classes, making testing and maintenance easier.

始终保持高内聚和低耦合。内聚的类具有单一、明确的目的;低耦合意味着类之间的依赖最小,使得测试和维护更容易。


12. OOP Summary and Exam Tips | OOP 总结与考试技巧

Mastering OOP principles—encapsulation, inheritance, polymorphism—is critical for top marks in Edexcel A-Level Computer Science. Practice writing and tracing pseudocode for class definitions, object creation, and method calls.

掌握 OOP 原则——封装、继承、多态——对于在 Edexcel A-Level 计算机科学考试中取得高分至关重要。多练习编写和跟踪类定义、对象创建和方法调用的伪代码。

In long-answer questions, explicitly link your solution back to OOP concepts; for example, explain how encapsulation protects data from invalid states. Use correct terminology consistently.

在长答题中,将你的解决方案明确关联到 OOP 概念;例如,解释封装如何保护数据免受无效状态的影响。始终使用正确的术语。

Revise UML class diagrams to represent classes, attributes, methods, and relationships. Many Edexcel papers include a diagram interpretation task where you must identify inheritance or composition.

复习 UML 类图以表示类、属性、方法和关系。许多 Edexcel 试卷中都包含图标解读任务,要求你识别继承或组合关系。

Published by TutorHao | Programming Revision Series | aleveler.com

更多咨询请联系16621398022(同微信)

Comments

屏轩国际教育cambridge primary/secondary checkpoint, cat4, ukiset,ukcat,igcse,alevel,PAT,STEP,MAT, ibdp,ap,ssat,sat,sat2课程辅导,国外大学本科硕士研究生博士课程论文辅导Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from aleveler.com

Subscribe now to keep reading and get access to the full archive.

Continue reading

Exit mobile version