📚 Object-Oriented Programming Fundamentals | 面向对象编程基础
Object-oriented programming (OOP) revolutionised software development by organising code around data rather than logic. In this article, we explore the core principles that underpin modern high-level languages such as Java, Python, and C#, aligning with the Edexcel A-Level Computer Science specification. You will learn how classes and objects model real-world entities, and how encapsulation, inheritance, and polymorphism promote maintainable and reusable code.
面向对象编程(OOP)通过围绕数据而非逻辑来组织代码,彻底改变了软件开发。本文将探索支撑现代高级语言(如Java、Python和C#)的核心原则,与Edexcel A-Level计算机科学课程大纲保持一致。你将学习类和对象如何对现实世界实体进行建模,以及封装、继承和多态如何促进可维护、可复用的代码。
1. What Is Object-Oriented Programming? | 什么是面向对象编程?
OOP is a programming paradigm that uses ‘objects’ – self-contained units combining data and behaviour – to design applications. Unlike procedural programming, which focuses on a sequence of instructions, OOP structures software as a collection of interacting objects. This approach mirrors how we perceive the real world, making it easier to manage complexity.
面向对象编程是一种使用“对象”(结合了数据与行为的独立单元)来设计应用程序的编程范式。与关注指令序列的过程式编程不同,OOP 将软件构建为相互交互的对象的集合。这种方法反映我们感知现实世界的方式,从而更容易管理复杂性。
2. Classes and Objects | 类与对象
A class is a blueprint or template that defines the attributes and behaviours common to a group of objects. For example, a Car class might define properties such as colour, make, and currentSpeed, as well as methods like accelerate() and brake(). An object is a specific instance of a class, created from that blueprint. In code, you might write:
类是一个蓝图或模板,定义了一组对象共有的属性和行为。例如,一个Car类可能定义颜色、品牌和当前速度等属性,以及 accelerate() 和 brake() 等方法。对象是该类的一个具体实例,根据该蓝图创建。在代码中,你可能会写:
Car myCar = new Car(‘Red’, ‘Toyota’);
Here, myCar is an object of type Car. The class defines the structure, while objects hold actual values and can invoke methods.
这里,myCar 是一个类型为 Car 的对象。类定义了结构,而对象保存实际值并可调用方法。
3. Attributes and Methods | 属性与方法
Attributes (also called fields or member variables) represent the state of an object. They are typically declared as variables inside the class. Methods define the behaviour of an object – the operations it can perform. A method can access and modify the object’s attributes, and may return a result. For instance, a BankAccount class might have an attribute balance and methods deposit(amount) and withdraw(amount).
属性(也称为字段或成员变量)表示对象的状态。它们通常在类内部声明为变量。方法定义了对象的行为——它能够执行的操作。方法可以访问和修改对象的属性,并可能返回一个结果。例如,一个BankAccount类可能有一个属性balance,以及deposit(amount)和withdraw(amount)方法。
4. Encapsulation | 封装
Encapsulation is the practice of hiding the internal details of an object and restricting direct access to some of its components. This is usually achieved by making attributes private and providing public getter and setter methods to interact with them. Encapsulation protects data from unintended modification and decouples the implementation from the interface. For example, a Temperature class could store Celsius internally but provide getFahrenheit() and setFahrenheit() methods, converting as needed.
封装是将对象的内部细节隐藏起来,并限制对其某些组件的直接访问的做法。这通常通过将属性设为私有,并提供公共的 getter 和 setter 方法来与它们交互来实现。封装保护数据免受意外修改,并将实现与接口解耦。例如,Temperature类可以在内部存储摄氏温度,但提供 getFahrenheit() 和 setFahrenheit() 方法,根据需要进行转换。
5. Access Modifiers | 访问修饰符
Access modifiers control the visibility of class members. The most common are:
访问修饰符控制类成员的可见性。最常见的有:
- public – accessible from any other class. / 可从任何其他类访问。
- private – accessible only within the same class. / 仅可在同一类中访问。
- protected – accessible within the same package and by subclasses. / 可在同一包内及由子类访问。
In A-Level contexts, understanding these modifiers is essential for implementing encapsulation and designing class hierarchies. Using private for attributes and public for methods is a standard convention.
在A-Level情境中,理解这些修饰符对于实现封装和设计类层次结构至关重要。对属性使用private,对方法使用public是一种标准惯例。
6. Constructors | 构造函数
A constructor is a special method invoked when an object is instantiated. It typically initialises the object’s attributes and performs any setup required. In many languages, the constructor has the same name as the class and no return type. You can overload constructors to provide multiple ways of creating an object. Example: a Student class might have a default constructor and a parameterised constructor Student(String name, int id).
构造函数是在对象实例化时调用的特殊方法。它通常初始化对象的属性并执行所需的任何设置。在许多语言中,构造函数与类同名且没有返回类型。你可以重载构造函数以提供多种创建对象的方式。例如:Student类可能有一个默认构造函数和一个带参数的构造函数 Student(String name, int id)。
7. Inheritance | 继承
Inheritance allows a new class (subclass) to adopt the attributes and methods of an existing class (superclass). This promotes code reuse and establishes a natural hierarchical relationship. For instance, a Dog class can inherit from an Animal class, gaining properties like age and methods like eat(), while adding its own specialised behaviours such as wagTail(). The keyword extends (in Java) or : (in C#) is used to denote inheritance.
继承允许新类(子类)采用现有类(超类)的属性和方法。这促进了代码复用,并建立了自然的层次关系。例如,Dog类可以继承自Animal类,获得如age属性和eat()方法,同时添加自己的特殊行为,如wagTail()。关键字extends(在Java中)或:(在C#中)用于表示继承。
8. Polymorphism | 多态
Polymorphism means ‘many forms’ and allows objects of different classes to be treated as objects of a common superclass. The most common type is method overriding, where a subclass provides a specific implementation of a method already defined in its superclass. A reference variable of the superclass type can point to a subclass object, and the correct overridden method is called at runtime (dynamic binding). For example:
多态意味着“多种形态”,允许将不同类的对象视为共同超类的对象。最常见的类型是方法重写,即子类为其超类中已定义的方法提供具体实现。超类类型的引用变量可以指向子类对象,并且在运行时(动态绑定)调用正确的重写方法。例如:
Animal a = new Dog(); a.speak();
If speak() is overridden in Dog, the Dog’s version executes, not Animal’s.
如果 speak() 在 Dog 中被重写,则执行 Dog 的版本,而不是 Animal 的。
9. Overriding vs Overloading | 重写与重载
A-Level specifications often require distinguishing between these two concepts. Overriding occurs when a subclass redefines a method with the same signature (name and parameter list) as in its superclass. It supports runtime polymorphism. Overloading happens when two or more methods in the same class share the same name but have different parameter lists (different number or types of parameters). Overloading is an example of compile-time polymorphism. In short: overriding = same signature, different class; overloading = same name, different parameters, same class.
A-Level大纲通常要求区分这两个概念。重写发生在子类重新定义与其超类中具有相同签名(名称和参数列表)的方法时。它支持运行时多态。重载发生在同一类中的两个或多个方法共享相同名称但具有不同参数列表(不同数量或类型的参数)时。重载是编译时多态的一个例子。简而言之:重写 = 相同签名,不同类;重载 = 相同名称,不同参数,同一类。
10. Abstraction | 抽象
Abstraction focuses on exposing only the essential details while hiding the complex implementation. Abstract classes and interfaces are key tools. An abstract class cannot be instantiated directly and may contain abstract methods (methods without a body) that subclasses must implement. An interface defines a contract of methods that implementing classes must fulfil. For example, an abstract class Shape may declare an abstract method calculateArea(), leaving subclasses like Circle and Rectangle to provide concrete formulas.
抽象专注于仅暴露关键细节而隐藏复杂实现。抽象类和接口是关键工具。抽象类不能直接实例化,并且可以包含抽象方法(没有方法体的方法),子类必须实现这些方法。接口定义了实现类必须履行的契约方法。例如,抽象类Shape可以声明一个抽象方法calculateArea(),留给Circle和Rectangle等子类提供具体公式。
11. Association, Aggregation, and Composition | 关联、聚合与组合
These terms describe relationships between classes beyond inheritance. Association is a generic ‘uses-a’ relationship, where one object interacts with another. Aggregation is a ‘has-a’ relationship where a whole is made up of parts, but the parts can exist independently (e.g., a Department has Employees). Composition is a stronger ‘has-a’ relationship where the parts cannot exist without the whole (e.g., a House is composed of Rooms; if the House is destroyed, the Rooms cease to exist). In UML, an empty diamond represents aggregation, and a filled diamond composition.
这些术语描述了类之间的除了继承之外的关系。关联是一种通用的“使用”关系,一个对象与另一个对象交互。聚合是一种“拥有”关系,整体由部分组成,但部分可以独立存在(例如,Department 拥有 Employees)。组合是一种更强的“拥有”关系,部分不能独立于整体而存在(例如,House 由 Rooms 组成;如果 House 被销毁,Rooms 也不复存在)。在 UML 中,空心菱形表示聚合,实心菱形表示组合。
12. Benefits and Real-World Relevance of OOP | 面向对象编程的优势与现实关联
OOP offers modularity (code is organised into discrete classes), reusability (inheritance and libraries), scalability, and security (encapsulation). These benefits are why languages like Python, Java, and C++ dominate in industry. In your A-Level coursework, applying OOP principles will improve code design and help you achieve higher marks in the programming project. Understanding these fundamentals not only prepares you for the exam but also for university-level computer science and professional software development.
OOP 提供了模块化(代码被组织为离散的类)、可复用性(继承和库)、可扩展性和安全性(封装)。这些优势正是 Python、Java 和 C++ 等在工业界占据主导地位的原因。在你的 A-Level 课程作业中,应用面向对象原则将改善代码设计,并帮助你在编程项目中取得更高分数。理解这些基础知识不仅为考试做准备,也为大学阶段的计算机科学及专业软件开发做好准备。
Published by TutorHao | Computer Science Revision Series | aleveler.com
更多咨询请联系16621398022(同微信)
屏轩国际教育cambridge primary/secondary checkpoint, cat4, ukiset,ukcat,igcse,alevel,PAT,STEP,MAT, ibdp,ap,ssat,sat,sat2课程辅导,国外大学本科硕士研究生博士课程论文辅导