📚 Object-Oriented Programming Concepts | 面向对象编程概念
Object-Oriented Programming (OOP) is a paradigm that organises software design around data, or objects, rather than functions and logic. It provides a clear modular structure for programs, making it easier to manage complexity, reuse code, and model real-world entities. For A-Level Computer Science under the Edexcel specification, mastering OOP is essential for understanding modern programming languages such as Java, C#, and Python. This article explains the core principles of OOP, including classes, objects, encapsulation, inheritance, and polymorphism, together with practical examples and exam-style considerations.
面向对象编程(OOP)是一种围绕数据(即对象)而非函数与逻辑来组织软件设计的范式。它为程序提供了清晰的模块化结构,使管理复杂性、代码复用和模拟现实世界实体变得更加容易。根据 Edexcel A-Level 计算机科学大纲,掌握面向对象编程对于理解 Java、C# 和 Python 等现代编程语言至关重要。本文解释了 OOP 的核心原则,包括类、对象、封装、继承和多态,并配有实例和考试风格的要点。
1. What is Object-Oriented Programming? | 什么是面向对象编程?
Object-Oriented Programming is a programming model centred on the concept of ‘objects’, which bundle data and the methods that operate on that data. It contrasts with procedural programming, where the focus is on writing procedures or functions that perform operations on separate data. OOP allows developers to create reusable blueprints called classes, from which individual objects are instantiated. This approach improves maintainability and scalability of code.
面向对象编程是一种以“对象”为核心的编程模型,对象将数据及操作这些数据的方法捆绑在一起。它与面向过程编程形成对比,后者的重点是编写对分离数据执行操作的过程或函数。OOP 允许开发人员创建称为类的可重用蓝图,再从这些蓝图实例化出各个对象。这种方法提高了代码的可维护性和可扩展性。
The four fundamental pillars of OOP are encapsulation, abstraction, inheritance, and polymorphism. Understanding these pillars enables a programmer to design systems that mirror real-world interactions and are easier to debug and extend.
面向对象编程的四大支柱是封装、抽象、继承和多态。理解这些支柱使程序员能够设计出反映现实世界交互且更易于调试和扩展的系统。
2. Classes and Objects | 类与对象
A class is a template or blueprint that defines the attributes (data) and behaviours (methods) that the objects of that type will have. For example, a class Car might have attributes such as colour, model, and speed, and methods like accelerate() and brake(). In code, a class is defined using the keyword class in most languages.
类是定义该类型对象将具有的属性(数据)和行为(方法)的模板或蓝图。例如,Car 类可能具有 colour、model 和 speed 等属性,以及 accelerate() 和 brake() 等方法。在代码中,大多数语言使用关键字 class 来定义类。
An object is a concrete instance of a class. Each object holds its own state, which is defined by the values of its attributes. You can create multiple objects from the same class, and each can have different attribute values while sharing the same structure and behaviour. For instance, myCar = new Car(‘red’, ‘SUV’) creates one Car object, and yourCar = new Car(‘blue’, ‘hatchback’) creates another.
对象是类的具体实例。每个对象都保持自己的状态,由其属性值定义。你可以从同一个类创建多个对象,每个对象可以有不同的属性值,同时共享相同的结构和行为。例如,myCar = new Car(‘red’, ‘SUV’) 创建一个 Car 对象,而 yourCar = new Car(‘blue’, ‘hatchback’) 创建另一个。
3. Encapsulation and Data Hiding | 封装与数据隐藏
Encapsulation is the mechanism of bundling data and the methods that act on that data into a single unit, a class. It also involves restricting direct access to some of an object’s components, a concept known as data hiding. By making attributes private and providing public getter and setter methods, a class can control how its data is read and modified.
封装是将数据及操作这些数据的方法捆绑到一个单一单元(即类)中的机制。它还涉及限制对对象某些组成部分的直接访问,这一概念称为数据隐藏。通过将属性设为私有并提供公共的 getter 和 setter 方法,类可以控制其数据被读取和修改的方式。
For example, a BankAccount class may have a private attribute balance. Public methods getBalance() and deposit(amount) are supplied to interact with the balance safely, ensuring the balance never becomes negative inappropriately. This prevents external code from setting an invalid state directly.
例如,BankAccount 类可以有一个私有属性 balance。提供公共方法 getBalance() 和 deposit(amount) 来安全地与余额交互,确保余额不会不适当地变为负数。这就阻止了外部代码直接设置无效状态。
- Access modifiers: private (accessible only within the same class), public (accessible from anywhere), and protected (accessible within the same class and subclasses).
- 访问修饰符:private(仅在同一类内可访问)、public(任何地方均可访问)和 protected(同一类及其子类内可访问)。
4. Inheritance | 继承
Inheritance allows a new class to acquire the properties and methods of an existing class. The existing class is called the parent, superclass, or base class, and the new class is the child, subclass, or derived class. This promotes code reuse and establishes a natural hierarchical relationship.
继承允许新类获取现有类的属性和方法。现有类称为父类、超类或基类,新类称为子类、派生类。这促进了代码复用并建立了自然的层次关系。
For instance, a Vehicle class may define a move() method. A Bike class can inherit from Vehicle and add unique attributes like gearCount while also being able to call move(). In UML class diagrams, inheritance is shown by an arrow with a hollow triangle pointing to the superclass.
例如,Vehicle 类可以定义一个 move() 方法。Bike 类可以从 Vehicle 继承,添加特有的属性如 gearCount,同时也能调用 move()。在 UML 类图中,继承用一个空心三角箭头指向超类来表示。
Many languages support single inheritance (a class inherits from one superclass), while interfaces allow a form of multiple inheritance. A subclass can override inherited methods to provide specific behaviour.
许多语言支持单继承(一个类继承自一个超类),而接口则允许一种多继承形式。子类可以重写继承的方法以提供特定行为。
5. Polymorphism | 多态
Polymorphism means ‘many forms’ and allows objects of different classes to be treated as objects of a common superclass. There are two main types: compile-time (method overloading) and runtime (method overriding). Runtime polymorphism is achieved through dynamic binding, where the method call is resolved based on the actual object type at runtime.
多态意为“多种形态”,允许将不同类的对象视为公共超类的对象来处理。主要有两种类型:编译时多态(方法重载)和运行时多态(方法重写)。运行时多态是通过动态绑定实现的,其中方法调用在运行时根据实际对象类型进行解析。
A classic example is a superclass Shape with a method draw(). Subclasses Circle, Square, and Triangle each override draw(). A reference of type Shape can point to any subclass object, and calling draw() will execute the subclass’s version. This provides flexibility and extensibility in code.
经典示例:超类 Shape 有一个方法 draw()。子类 Circle、Square 和 Triangle 各自重写 draw()。一个 Shape 类型的引用可以指向任何子类对象,调用 draw() 将执行子类版本。这为代码提供了灵活性和可扩展性。
Key distinction: Overloading is defining multiple methods in the same class with the same name but different parameter lists. Overriding is redefining a superclass method in a subclass with the same signature.
关键区别:重载是在同一个类中定义多个同名但参数列表不同的方法。重写是在子类中用相同的签名重新定义超类的方法。
6. Abstraction and Abstract Classes | 抽象与抽象类
Abstraction is the process of hiding complex implementation details and showing only the essential features of an object. It reduces programming complexity by focusing on what an object does instead of how it does it. Abstract classes and interfaces are the main tools for achieving abstraction in OOP.
抽象是隐藏复杂实现细节、只显示对象基本特征的过程。它通过关注对象做什么而非如何做来降低编程复杂度。抽象类和接口是在 OOP 中实现抽象的主要工具。
An abstract class is a class that cannot be instantiated and is designed to be subclassed. It may contain abstract methods (without a body) that must be implemented by concrete subclasses. For example, an abstract class Animal may declare an abstract method makeSound(), leaving each subclass to define the specific sound.
抽象类是不能被实例化的类,被设计为子类化。它可以包含抽象方法(没有方法体),这些方法必须由具体子类实现。例如,抽象类 Animal 可以声明一个抽象方法 makeSound(),让每个子类定义具体的声音。
In UML, abstract classes and methods are denoted by italics or the {abstract} constraint. Interfaces are similar but can only declare method signatures and constants, without any implementation (in languages like Java).
在 UML 中,抽象类和方法用斜体或 {abstract} 约束表示。接口类似,但只能声明方法签名和常量,不能包含实现(如在 Java 等语言中)。
7. Interfaces | 接口
An interface defines a contract of behaviours that a class must implement. It contains method signatures but no method bodies. A class that implements an interface must provide concrete definitions for all declared methods. This enables multiple classes to share a common behaviour without being related by inheritance.
接口定义了一个类必须实现的行为契约。它包含方法签名但没有方法体。实现接口的类必须为所有声明的方法提供具体定义。这使得多个类可以共享共同行为,而无需通过继承相关联。
For example, a Playable interface might declare methods play(), pause(), and stop(). Both a MusicPlayer and a VideoPlayer can implement this interface, but each will define the methods according to its own functionality. Interfaces support polymorphism and design flexibility.
例如,Playable 接口可以声明 play()、pause() 和 stop() 方法。MusicPlayer 和 VideoPlayer 都可以实现此接口,但每个将根据其自身功能定义这些方法。接口支持多态和设计灵活性。
Unlike abstract classes, a class can implement multiple interfaces, thereby providing a solution to the limitation of single inheritance. This is particularly useful in building large-scale systems.
与抽象类不同,一个类可以实现多个接口,从而为单继承的限制提供了解决方案。这在构建大型系统时尤其有用。
8. Access Modifiers in Depth | 深入理解访问修饰符
Access modifiers control the visibility and accessibility of class members. In typical OOP languages like Java and TypeScript, the primary modifiers are:
- public: accessible from any other class.
- private: accessible only within the declaring class.
- protected: accessible within the same package and by subclasses.
- default (package-private): accessible only within the same package (no keyword).
Proper use of access modifiers enforces encapsulation and protects the integrity of the data.
访问修饰符控制类成员的可见性和可访问性。在典型的面向对象语言如 Java 和 TypeScript 中,主要的修饰符有:
- public:可从任何其他类访问。
- private:仅可在声明类中访问。
- protected:可在同一包及子类中访问。
- default(包私有):仅在同一包内可访问(无关键字)。
正确使用访问修饰符可以加强封装并保护数据完整性。
At A-Level, you should be able to justify the choice of modifier for given attributes and methods and understand the implications of exposing data directly.
在 A-Level 中,你应该能够为给定的属性和方法合理选择修饰符,并理解直接暴露数据的后果。
9. Constructors and Destructors | 构造函数与析构函数
A constructor is a special method that is automatically called when an object is instantiated. It typically initialises the object’s attributes. Constructors have the same name as the class and no return type. They can be overloaded to provide multiple ways of creating objects with different initial values.
构造函数是一个特殊的方法,在对象实例化时自动调用。它通常初始化对象的属性。构造函数与类同名且无返回类型。它们可以被重载,以提供用不同初始值创建对象的多种方式。
For example, a Book class may have a default constructor Book() that sets title to ‘Unknown’, and a parameterised constructor Book(String t, String a) that sets title and author. In languages such as Java, if no constructor is written, a default no-argument constructor is provided by the compiler.
例如,Book 类可以有一个默认构造函数 Book() 将标题设为 ‘Unknown’,以及一个带参构造函数 Book(String t, String a) 设置标题和作者。在 Java 等语言中,如果不编写构造函数,编译器会提供一个无参默认构造函数。
A destructor (or finalizer) is called when an object is destroyed, used to release resources like file handles. In languages with automatic garbage collection (e.g., Java, Python), destructors are less prominent but may be implemented via finalize() or __del__().
析构函数(或终结器)在对象被销毁时调用,用于释放文件句柄等资源。在具有自动垃圾回收的语言中(如 Java、Python),析构函数不太突出,但可以通过 finalize() 或 __del__() 实现。
10. Association, Aggregation, and Composition | 关联、聚合与组合
These terms describe relationships between classes beyond simple inheritance. They represent ‘has-a’ relationships with varying degrees of ownership and lifecycle dependency.
这些术语描述了类之间除简单继承之外的关系。它们代表具有不同程度所有权和生命周期依赖关系的“has-a”关系。
- Association: A general bi-directional relationship where one class uses another. Example: a Teacher and a Student are associated through a classroom; neither owns the other.
- 关联:一种通用的双向关系,一个类使用另一个类。示例:Teacher 与 Student 通过教室相关联;两者互不拥有对方。
- Aggregation: A special form of association representing a ‘whole-part’ relationship where the part can exist independently of the whole. Example: a Department has Professors; if the department closes, the professors can still exist.
- 聚合:关联的一种特殊形式,表示“整体-部分”关系,其中部分可以独立于整体存在。示例:一个 Department 包含 Professors;如果部门关闭,教授仍然可以存在。
- Composition: A stronger form of aggregation where the part cannot exist without the whole. The lifecycle of the part is tied to the whole. Example: a House is composed of Rooms; destroy the house, and the rooms are destroyed.
- 组合:聚合的一种更强形式,部分不能没有整体而存在。部分的生命周期与整体绑定。示例:一个 House 由 Rooms 组成;如果房子被毁,房间也被毁。
In UML, association is shown by a solid line, aggregation with an empty diamond at the whole, composition with a filled diamond.
在 UML 中,关联用实线表示,聚合在整体端用空心菱形表示,组合用实心菱形。
11. UML Class Diagrams | UML 类图
Unified Modeling Language (UML) class diagrams are a standard way to visualise the structure of an OOP system. A class is represented as a rectangle divided into three compartments: the class name, attributes, and methods. Visibility symbols (+ public, – private, # protected) prefix the members.
统一建模语言(UML)类图是可视化 OOP 系统结构的标准方式。一个类表示为矩形,分为三个区域:类名、属性和方法。可见性符号(+ 公共,- 私有,# 保护)作为成员的前缀。
For example:
Car
– colour: string
– speed: int
+ accelerate(): void
+ brake(): void
Relationships like inheritance (hollow triangle arrow), association, aggregation, and implementation (dashed line with hollow triangle) are drawn between classes. Being able to interpret and create simple UML diagrams is a valuable skill for A-Level assignments and exams.
类之间会绘制继承(空心三角箭头)、关联、聚合和实现(带空心三角的虚线)等关系。能够解释和创建简单的 UML 图是 A-Level 作业和考试中的一项宝贵技能。
12. OOP Design Principles and Exam Tips | 面向对象设计原则与应试技巧
While not always explicitly assessed, understanding key design principles helps write robust OOP code. The SOLID principles (Single Responsibility, Open/Closed, Liskov Substitution, Interface Segregation, Dependency Inversion) provide guidelines for class design that promotes maintainability.
虽然不一定明确评估,但理解关键设计原则有助于编写健壮的 OOP 代码。SOLID 原则(单一职责、开闭原则、里氏替换、接口隔离、依赖反转)为促进可维护性的类设计提供了指导。
For the Edexcel A-Level written exam and non-exam assessment (NEA), you should be able to:
- Define classes, objects, and the four pillars of OOP.
- Interpret and write small code snippets demonstrating encapsulation, inheritance, and polymorphism.
- Draw simple UML class diagrams.
- Explain the advantages of OOP over procedural programming.
- Justify the use of private attributes with public methods.
在 Edexcel A-Level 笔试和非考试评估(NEA)中,你需要能够:
- 定义类、对象和 OOP 的四大支柱。
- 解释并编写演示封装、继承和多态的小段代码。
- 绘制简单的 UML 类图。
- 解释 OOP 相对于面向过程编程的优势。
- 为使用私有属性和公共方法提供正当理由。
Practise by modelling real-world scenarios (e.g., a library system, a banking application) and identifying classes, relationships, and behaviours. This will solidify your understanding and prepare you for practical programming tasks.
通过模拟现实世界场景(例如图书馆系统、银行应用程序)并确定类、关系和行为来进行练习。这将巩固你的理解,为实际的编程任务做好准备。
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课程辅导,国外大学本科硕士研究生博士课程论文辅导Cancel reply