Object-Oriented Programming: Principles and Practice | 面向对象编程:原则与实践

📚 Object-Oriented Programming: Principles and Practice | 面向对象编程:原则与实践

Object-oriented programming (OOP) is a fundamental paradigm in the Edexcel A Level programming syllabus. It organises software design around objects rather than functions and logic, making it easier to model complex real-world systems. This article covers the core OOP principles, terminology and practical techniques you need to master for exam success.

面向对象编程(OOP)是 Edexcel A Level 编程大纲中的基础范式。它围绕对象而非函数与逻辑来组织软件设计,使得模拟复杂的现实世界系统更为容易。本文涵盖了你需要掌握的 OOP 核心原则、术语和实践技巧,助你在考试中取得成功。


1. Overview of Programming Paradigms | 编程范式概述

A programming paradigm is a style or way of programming. Two major paradigms are procedural and object-oriented. Procedural programming uses a linear top-down approach with functions operating on data, whereas OOP bundles data and the methods that act on it into objects.

编程范式是一种编程风格或方式。两大主要范式是过程式编程和面向对象编程。过程式编程采用线性的自顶向下方法,用函数操作数据;而 OOP 将数据及作用于数据的方法封装进对象中。

In procedural languages like C, data is often exposed and can be modified by any function, leading to potential errors. OOP addresses this by encapsulating data within objects and enforcing controlled interaction through methods.

在像 C 这样的过程式语言中,数据通常是暴露的,可以被任何函数修改,由此可能导致错误。OOP 通过将数据封装在对象中,并通过方法强制执行受控交互来解决这个问题。


2. Defining Classes and Objects | 定义类与对象

A class is a blueprint or template that defines the attributes (fields) and behaviours (methods) of a type of object. An object is an instance of a class, created at runtime with its own state.

类是定义某一类型对象的属性(字段)和行为(方法)的蓝图或模板。对象是类的实例,在运行时创建并拥有自己的状态。

For example, a class Car might have attributes like colour and speed, and methods like accelerate(). The statement Car myCar = new Car(); creates an object of type Car.

例如,一个 Car 类可能有 colourspeed 等属性,以及 accelerate() 等方法。语句 Car myCar = new Car(); 会创建一个 Car 类型的对象。

In the exam you should be able to identify classes, objects, attributes and methods from given scenarios and translate them into simple class diagrams.

在考试中,你应能从给定场景中识别类、对象、属性和方法,并将其转化为简单的类图。


3. Encapsulation: Protecting Data | 封装:保护数据

Encapsulation is the bundling of data with the methods that operate on that data, restricting direct access to some of an object’s components. This is usually achieved using access modifiers.

封装是将数据与操作该数据的方法捆绑在一起,限制对对象某些组件的直接访问。这通常通过访问修饰符来实现。

Encapsulation helps maintain data integrity by preventing outside code from accidentally modifying internal state. It also allows internal implementation to change without affecting other parts of the program.

封装通过防止外部代码意外修改内部状态,有助于维护数据完整性。它还允许内部实现发生更改而不影响程序的其他部分。

A typical example is making all fields private and providing public getter and setter methods to read and update values safely.

一个典型的例子是将所有字段设为 private,并提供 public 的 getter 和 setter 方法以安全地读取和更新值。


4. Inheritance: Building Hierarchies | 继承:构建层次结构

Inheritance enables a new class (subclass) to acquire the properties and methods of an existing class (superclass). This promotes code reuse and establishes a natural hierarchical relationship.

继承使新类(子类)能够获得现有类(超类)的属性和方法。这促进了代码重用并建立了自然的层次关系。

The keyword extends is used in Java-style languages to indicate inheritance. A subclass can add its own fields and methods, override inherited methods, and access the superclass constructor with super().

在 Java 风格的语言中使用关键字 extends 表示继承。子类可以添加自己的字段和方法,重写继承的方法,并使用 super() 访问超类的构造函数。

class Dog extends Animal { … }

class Dog extends Animal { … }

Multiple inheritance (where a class can inherit from more than one superclass) is not allowed in Java but is supported in languages like C++. Edexcel focuses on single inheritance and interface implementation.

多重继承(一个类可以继承多个超类)在 Java 中不允许,但在 C++ 等语言中受支持。爱德思考试侧重点在于单一继承和接口实现。


5. Polymorphism: Many Forms | 多态:多种形态

Polymorphism 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 already defined in its superclass.

多态允许将不同类的对象当作共同超类的对象来对待。最常见的形式是方法重写,即子类提供对超类中已定义方法的具体实现。

Dynamic method dispatch determines at runtime which version of a method to invoke based on the actual object type, not the reference type. This is central to OOP flexibility.

动态方法调度在运行时根据实际对象类型而非引用类型来决定调用哪个版本的方法。这对 OOP 的灵活性至关重要。

  • Overriding: same method signature, different implementation in subclass.

    重写:相同的方法签名,在子类中有不同的实现。

  • Overloading: same method name but different parameter lists within the same class.

    重载:相同的方法名称但在同一个类中具有不同的参数列表。


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

An abstract class cannot be instantiated directly and is designed to be subclassed. It may contain abstract methods (without a body) that subclasses must implement, as well as concrete methods with code.

抽象类不能直接实例化,其设计目的是被继承。它可以包含抽象方法(无方法体),子类必须实现这些方法,同时也可以包含带有代码的具体方法。

An interface defines a contract of methods that implementing classes must fulfil. In Java, interfaces can have default and static methods; all methods are public abstract by default prior to Java 8. An interface supports complete abstraction and multiple implementation.

接口定义了一个方法契约,实现类必须履行该契约。在 Java 中,接口可以有默认方法和静态方法;在 Java 8 之前,所有方法默认为 public abstract。接口支持完全抽象和多重实现。

Feature Abstract Class Interface
Instantiation Cannot be instantiated Cannot be instantiated
Methods with body Allowed Yes (default/static from Java 8)
Multiple inheritance Not supported A class can implement many

7. Constructors and Object Lifecycle | 构造函数与对象生命周期

A constructor is a special method invoked when an object is created, typically sharing the class name. It initialises the object’s state. A class can have multiple constructors through overloading.

构造函数是在创建对象时调用的特殊方法,通常与类名相同。它用于初始化对象的状态。一个类可以通过重载拥有多个构造函数。

The default constructor is provided automatically if no constructor is explicitly defined. Once a parameterised constructor is written, the default disappears, so you must define it explicitly if needed.

如果没有显式定义构造函数,会自动提供默认构造函数。一旦编写了带参数的构造函数,默认构造函数就会消失,因此如果需要就必须显式定义。

Objects are destroyed by a garbage collector in managed languages like Java. Destructors (finalisers) are rarely used nowadays; resource cleanup is often handled via a close() method or try-with-resources.

在 Java 等托管语言中,对象由垃圾回收器销毁。析构函数(终结器)现在已很少使用;资源清理通常通过 close() 方法或 try-with-resources 处理。


8. Access Modifiers in Detail | 访问修饰符详解

Access modifiers control the visibility of classes, methods and fields. They are essential for enforcing encapsulation. The main modifiers are public, private, protected and package-private (default).

访问修饰符控制类、方法和字段的可见性,对于强制封装至关重要。主要的修饰符有 publicprivateprotected 和包私有(默认)。

Modifier 中文 Visibility
public 公开 Visible everywhere
protected 受保护 Same package + subclasses
default 默认 Same package only
private 私有 Same class only

In OOP design, fields are usually private to protect data, while methods are public to provide a controlled interface. The protected modifier is useful when subclasses need direct access to superclass members.

在 OOP 设计中,字段通常为 private 以保护数据,而方法为 public 以提供受控接口。当子类需要直接访问超类成员时,protected 修饰符十分有用。


9. Static Members and Class Variables | 静态成员与类变量

A static member belongs to the class itself rather than any specific instance. Static variables are shared across all objects of the class, and static methods can be called without creating an object.

static 成员属于类本身而非任何特定实例。静态变量在该类的所有对象之间共享,而静态方法无需创建对象即可调用。

The classic example is a Math class containing only static methods like Math.sqrt(). Static fields are often used for constants or to maintain a count of instances created.

经典的例子是仅包含 Math.sqrt() 等静态方法的 Math 类。静态字段常用于常量或维护已创建实例的计数。

Be careful: static methods cannot directly access instance variables or call non-static methods because there is no implicit this reference.

请注意:静态方法不能直接访问实例变量或调用非静态方法,因为没有隐含的 this 引用。


10. Introduction to UML Class Diagrams | UML 类图简介

Unified Modelling Language (UML) class diagrams are a standard way to visualise the structure of an OOP system. A class box is divided into three compartments: name, attributes, and methods.

统一建模语言(UML)类图是可视化 OOP 系统结构的标准方式。一个类框分为三层:名称、属性和方法。

Access modifiers in UML are denoted by ‘+’ for public, ‘-‘ for private, and ‘#’ for protected. Inheritance is shown with a solid line and an unfilled triangular arrowhead pointing to the superclass.

UML 中的访问修饰符用 ‘+’ 表示 public、’-‘ 表示 private、’#’ 表示 protected。继承用一条实线和一个指向超类的空心三角箭头表示。

Vehicle ←— Car (inheritance)

Vehicle ←— Car (继承)

Additionally, associations, aggregation and composition can model ‘has-a’ relationships. Edexcel expects you to interpret and draw simple class diagrams.

此外,关联、聚合和组合可以模拟“拥有”关系。爱德思考纲期望你能够解释并绘制简单的类图。


11. Advantages and Disadvantages of OOP | OOP 的优缺点

OOP offers clear benefits: modularity through classes, code reuse via inheritance, flexibility through polymorphism, and improved security with encapsulation. It is well-suited for large, complex software projects.

OOP 具有明显优势:通过类实现模块化、通过继承实现代码重用、通过多态实现灵活性,并通过封装提高安全性。它非常适合大型复杂的软件项目。

However, OOP can introduce overhead. It may lead to larger program size, deeper learning curves, and performance costs due to many objects and dynamic dispatch. Not every problem requires OOP; over-engineering is a common pitfall.

但是,OOP 可能带来额外开销。它可能导致程序体积更大、学习曲线更陡峭,并因众多对象和动态调度产生性能成本。并非每个问题都需要 OOP;过度设计是一个常见的陷阱。

  • Advantage: easier maintenance and extension of code.

    优点:代码更易于维护和扩展。

  • Disadvantage: can be challenging to design the correct class hierarchy upfront.

    缺点:前期设计正确的类层次结构可能具有挑战性。


12. Practical OOP Example: A Banking System | 实践案例:银行系统

Consider a simple banking system with an abstract Account class and subclasses SavingsAccount and CurrentAccount. Each account has a balance and an account number. The abstract method withdraw(amount) is implemented differently depending on overdraft rules.

设想一个简单的银行系统,包含抽象类 Account 和子类 SavingsAccountCurrentAccount。每个账户都有余额和账号。抽象方法 withdraw(amount) 根据透支规则实现得各不相同。

The SavingsAccount might override withdraw() to prevent withdrawals that would drop the balance below a minimum threshold, while CurrentAccount might allow an arranged overdraft.

SavingsAccount 可能重写 withdraw() 以防止提取后的余额低于最低阈值,而 CurrentAccount 可能允许约定的透支。

All account objects are stored in a list of type Account; polymorphism allows iterating through the list and calling withdraw() without knowing the exact subclass. This demonstrates encapsulation, inheritance, and polymorphism working together.

所有账户对象都存储在一个类型为 Account 的列表中;通过多态可以遍历列表并调用 withdraw() 而无需知道确切的子类。这展示了封装、继承和多态协同工作的情况。


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