📚 Object-Oriented Programming Core Principles | 面向对象编程核心原则
Object-Oriented Programming (OOP) is a paradigm that organises code around objects rather than functions. In A-Level Computer Science, understanding OOP is essential for modelling real-world systems, managing complexity, and promoting code reuse. This article explores the foundational concepts of OOP, including encapsulation, inheritance, polymorphism, and abstraction, along with practical examples in a C-style syntax commonly used in exam contexts.
面向对象编程(OOP)是一种围绕对象而非函数来组织代码的范式。在A-Level计算机科学中,理解OOP对于模拟真实世界系统、管理复杂性和促进代码重用至关重要。本文探讨OOP的基本概念,包括封装、继承、多态和抽象,并通过考试中常见的类C语法提供实际示例。
1. Classes and Objects | 类与对象
A class is a blueprint for creating objects. It defines attributes (data) and methods (behaviour) that the objects will possess. An object is an instance of a class, with its own state and access to the class’s methods.
类是创建对象的蓝图。它定义了对象将拥有的属性(数据)和方法(行为)。对象是类的实例,具有自己的状态,并可以访问类的方法。
For example, a Car class might have attributes like colour and speed, and methods like accelerate(). Each car object will have specific values for these attributes.
例如,一个Car类可能具有colour和speed等属性,以及accelerate()等方法。每个汽车对象对这些属性都有具体的值。
In pseudocode, declaring a class and creating an object looks like this:
在伪代码中,声明类并创建对象如下所示:
CLASS Car
PRIVATE colour: STRING
PUBLIC PROCEDURE new(givenColour)
colour ← givenColour
ENDPROCEDURE
ENDCLASS
myCar ← NEW Car(“red”)
2. Encapsulation | 封装
Encapsulation is the practice of hiding an object’s internal state and requiring all interaction to occur through well-defined methods. It protects data from unintended modification and reduces coupling between components.
封装是隐藏对象内部状态,并要求所有交互都通过明确定义的方法进行的做法。它保护数据免受意外修改,并降低组件之间的耦合度。
Attributes are typically declared as private, and public getter and setter methods are provided to access or update them. This allows validation or transformation of data before it is stored.
属性通常被声明为私有的,并提供公共的 getter 和 setter 方法来访问或更新它们。这样可以在存储数据之前对其进行验证或转换。
A typical encapsulated class:
一个典型的封装类:
CLASS Student
PRIVATE name: STRING
PRIVATE grade: INTEGER
PUBLIC PROCEDURE setGrade(newGrade)
IF newGrade ≥ 0 AND newGrade ≤ 100 THEN
grade ← newGrade
ENDIF
ENDPROCEDURE
ENDCLASS
3. Inheritance | 继承
Inheritance allows a new class (subclass) to derive attributes and methods from an existing class (superclass). It promotes code reuse and establishes a hierarchical relationship between types.
继承允许新类(子类)从现有类(超类)派生属性和方法。它促进了代码重用,并在类型之间建立了层次关系。
The subclass can extend or override the behaviour of the superclass. For example, a Dog class might inherit from an Animal class and add a bark() method.
子类可以扩展或重写超类的行为。例如,Dog类可以继承Animal类,并添加bark()方法。
In pseudocode, inheritance uses the INHERITS keyword:
在伪代码中,继承使用INHERITS关键字:
CLASS Animal
PUBLIC PROCEDURE eat()
…
ENDCLASS
CLASS Dog INHERITS Animal
PUBLIC PROCEDURE bark()
…
ENDCLASS
4. Polymorphism | 多态
Polymorphism means “many forms.” It enables a single interface to represent different underlying data types. In OOP, this often occurs through method overriding, where a subclass provides a specific implementation of a method already defined in its superclass.
多态意为“多种形态”。它使单个接口能够表示不同的底层数据类型。在OOP中,这通常通过方法重写来实现,即子类提供已在超类中定义的方法的特定实现。
For instance, a Shape superclass might define a method draw(), and subclasses Circle and Rectangle implement it differently. Code that calls draw() on a Shape reference will execute the correct version.
例如,Shape超类可能定义一个draw()方法,而Circle和Rectangle子类以不同的方式实现它。在Shape引用上调用draw()的代码将执行正确的版本。
This reduces conditional logic and makes systems extensible.
这减少了条件逻辑,并使系统具有可扩展性。
- Inheritance polymorphism – overriding methods in subclasses.
- Interface polymorphism – different classes implementing the same set of method signatures.
- 继承多态 – 在子类中重写方法。
- 接口多态 – 不同的类实现相同的方法签名集。
5. Abstraction | 抽象
Abstraction involves focusing on the essential qualities of an object rather than the specific details. In OOP, abstract classes and interfaces provide a way to define what an object should do without specifying how it does it.
抽象涉及关注对象的本质特性,而不是具体细节。在OOP中,抽象类和接口提供了一种定义对象应该做什么而不指定其具体实现的方式。
An abstract class cannot be instantiated; it is designed to be inherited by subclasses that provide concrete implementations for its abstract methods.
抽象类不能实例化;它被设计为由子类继承,子类为其抽象方法提供具体的实现。
Abstract methods are declared without a body:
抽象方法声明时没有方法体:
ABSTRACT CLASS Vehicle
ABSTRACT PROCEDURE move()
ENDCLASS
CLASS Car INHERITS Vehicle
PUBLIC PROCEDURE move()
OUTPUT “Car is driving”
ENDPROCEDURE
ENDCLASS
6. Constructors | 构造方法
A constructor is a special method automatically called when an object is instantiated. It initialises the object’s attributes and performs any setup required.
构造方法是一种特殊的方法,在实例化对象时自动调用。它初始化对象的属性并执行所需的任何设置。
Constructors often have the same name as the class and can accept parameters to set initial values. If no constructor is defined, a default constructor is provided.
构造方法通常与类同名,并可接受参数以设置初始值。如果没有定义构造方法,则提供默认的构造方法。
Example with multiple constructors (overloading):
带有多个构造方法(重载)的示例:
CLASS Book
PRIVATE title: STRING
PUBLIC PROCEDURE new()
title ← “Unknown”
ENDPROCEDURE
PUBLIC PROCEDURE new(bookTitle)
title ← bookTitle
ENDPROCEDURE
ENDCLASS
7. Access Modifiers | 访问修饰符
Access modifiers control the visibility of class members. The most common are public, private, and protected.
访问修饰符控制类成员的可见性。最常见的是public、private和protected。
- Public – accessible from anywhere.
- Private – accessible only within the same class.
- Protected – accessible within the class and its subclasses.
- Public – 任何地方都可访问。
- Private – 仅在同一类内可访问。
- Protected – 可在类及其子类中访问。
Using the appropriate modifier is crucial for encapsulation and maintaining code integrity.
使用适当的修饰符对于封装和维护代码完整性至关重要。
8. Method Overloading vs. Overriding | 方法重载与重写
Method overloading means defining multiple methods with the same name but different parameter lists within the same class. The compiler selects the correct method based on the arguments passed.
方法重载意味着在同一个类中定义多个名称相同但参数列表不同的方法。编译器根据传递的参数选择正确的方法。
Method overriding occurs when a subclass provides its own implementation of a method that is already defined in its superclass. The method signature must be identical.
方法重写发生在子类为其超类中已定义的方法提供自己的实现时。方法签名必须完全相同。
Key differences:
主要区别:
| Aspect | Overloading | Overriding |
|---|---|---|
| Parameters | Must differ | Must be identical |
| Inheritance | Not required | Required (subclass-superclass) |
| Purpose | Increase readability | Polymorphism |
9. Interfaces and Abstract Classes | 接口与抽象类
An interface defines a contract of methods that a class must implement, without containing any concrete method bodies. It provides a way to achieve full abstraction.
接口定义了一个类必须实现的方法契约,不包含任何具体的方法体。它提供了一种实现完全抽象的方式。
An abstract class, in contrast, can contain both abstract methods (without bodies) and concrete methods (with bodies). It can also have instance variables.
相反,抽象类可以包含抽象方法(无方法体)和具体方法(具有方法体)。它还可以具有实例变量。
Deciding when to use each:
决定何时使用它们:
- Use an interface when unrelated classes need to share a common design.
- Use an abstract class when classes are closely related and share code.
- 当不相关的类需要共享一个共同的设计时,使用接口。
- 当类关系紧密且共享代码时,使用抽象类。
10. Association, Aggregation, and Composition | 关联、聚合与组合
These terms describe relationships between objects:
这些术语描述了对象之间的关系:
- Association – a general “uses-a” relationship; objects know about each other but can exist independently.
- Aggregation – a “has-a” relationship where the contained object can exist independently of the container (e.g., a Department has Employees, but Employees can exist without the Department).
- Composition – a stronger “has-a” relationship where the contained object cannot exist without the container (e.g., a House has Rooms; if the House is destroyed, the Rooms are destroyed).
- 关联 – 一个一般的“使用”关系;对象彼此了解,但可以独立存在。
- 聚合 – 一个“拥有”关系,其中被包含的对象可以独立于容器存在(例如,一个部门有员工,但员工可以在没有部门的情况下存在)。
- 组合 – 一种更强的“拥有”关系,其中被包含的对象不能脱离容器而存在(例如,房子有房间;如果房子被摧毁,房间也被摧毁)。
This distinction helps in designing robust object-oriented systems.
这种区别有助于设计健壮的面向对象系统。
11. Advantages of OOP | 面向对象编程的优势
OOP offers several benefits over procedural programming: modularity through classes, easier maintenance and debugging, code reusability via inheritance, and flexibility through polymorphism. It also models real-world entities naturally, making design more intuitive.
OOP相对于过程式编程提供了几个优点:通过类实现模块化,更易于维护和调试,通过继承实现代码重用,以及通过多态获得灵活性。它还自然地模拟了现实世界的实体,使设计更直观。
In large systems, OOP facilitates teamwork by allowing different developers to work on separate classes with well-defined interfaces.
在大型系统中,OOP通过允许不同的开发人员在具有明确定义接口的独立类上工作,促进了团队合作。
12. Common Pitfalls and Best Practices | 常见陷阱与最佳实践
While OOP is powerful, misuse can lead to overly complex hierarchies, deep inheritance trees that are hard to follow, and classes that try to do too much (violating the Single Responsibility Principle).
虽然OOP很强大,但误用可能导致过于复杂的层次结构、难以理解的深层继承树以及试图做太多事情的类(违反单一职责原则)。
Best practices include favouring composition over inheritance, keeping classes focused on one responsibility, using private attributes with public accessors, and designing for interfaces rather than concrete implementations.
最佳实践包括优先使用组合而非继承,使类专注于一个职责,使用私有属性和公共访问器,以及为接口而非具体实现进行设计。
Understanding these principles will help you write clear, efficient OOP code and succeed in your A-Level examinations.
理解这些原则将有助于你编写清晰、高效的OOP代码,并在A-Level考试中取得成功。
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