📚 Object-Oriented Programming: Classes, Inheritance, Encapsulation, and Polymorphism | 面向对象编程:类、继承、封装与多态
Object-oriented programming (OOP) is a programming paradigm built around objects that contain both data and the methods that operate on that data. For Edexcel A-Level Computer Science, you need to understand how classes, objects, inheritance, encapsulation and polymorphism support modular, reusable and maintainable code. This article explains the core OOP concepts with Python and Java examples, and highlights common exam pitfalls.
面向对象编程(OOP)是一种围绕对象构建的编程范式,对象既包含数据,也包含操作这些数据的方法。在 Edexcel A-Level 计算机科学中,你需要理解类、对象、继承、封装和多态如何支持模块化、可复用和可维护的代码。本文通过 Python 和 Java 示例解释核心 OOP 概念,并指出常见考试易错点。
1. Programming Paradigms and the Need for OOP | 编程范式与面向对象编程的必要性
A programming paradigm is a fundamental style of organising code. Procedural programming focuses on functions and step-by-step instructions, while OOP groups related data and behaviour into objects. Edexcel requires you to recognise that OOP improves modularity, reusability and maintainability for large or complex systems.
编程范式是组织代码的基本风格。过程式编程专注于函数和逐步指令,而 OOP 将相关数据和行为组合成对象。Edexcel 要求你认识到,对于大型或复杂系统,OOP 能提高模块化、可复用性和可维护性。
- Procedural: data is stored in separate variables and passed to functions. | 过程式:数据存储在单独的变量中并传递给函数。
- OOP: data and the functions that manipulate it are bundled together in a single object. | 面向对象:数据和操作数据的函数被打包在同一个对象中。
- Key benefit: objects model real-world entities, making code easier to understand and extend. | 关键优势:对象模拟现实世界实体,使代码更易理解和扩展。
2. Classes and Objects | 类与对象
A class is a blueprint or template that defines the attributes and methods shared by all objects of that type. An object is a concrete instance of a class. For example, the class Car may define the properties colour and topSpeed, while an object could be myCar with the values “red” and 120.
类是定义该类型所有对象共享的属性和方法的蓝图或模板。对象是类的具体实例。例如,类 Car 可以定义属性 colour 和 topSpeed,而对象可以是 myCar,其值为 “red” 和 120。
Class → Object: instantiation (类 → 对象:实例化)
In Java, you create an object using the new keyword: Car myCar = new Car();. In Python, you call the class name like a function: myCar = Car(). Both allocate memory for the new instance and return a reference to it.
在 Java 中,使用 new 关键字创建对象:Car myCar = new Car();。在 Python 中,像函数一样调用类名:myCar = Car()。两者都会为新实例分配内存并返回其引用。
3. Attributes and Methods | 属性与方法
Attributes store the state of an object, such as brand or fuelLevel. Methods define the behaviour of an object, such as accelerate() or brake(). In OOP, attributes should normally be accessed through methods to preserve encapsulation.
属性存储对象的状态,例如 brand 或 fuelLevel。方法定义对象的行为,例如 accelerate() 或 brake()。在 OOP 中,属性通常应通过方法访问,以保持封装性。
In Python, the first parameter of an instance method must be self, which refers to the current object. In Java, the implicit reference this serves the same purpose, but it does not appear in the parameter list.
在 Python 中,实例方法的第一个参数必须是 self,它指向当前对象。在 Java 中,隐式引用 this 具有相同的作用,但它不会出现在参数列表中。
4. Constructors and Instantiation | 构造函数与实例化
A constructor is a special method that runs automatically when a new object is created. It initialises attribute values and sets the object into a valid starting state. Python uses __init__, while Java uses a method with the same name as the class and no return type.
构造函数是一种特殊方法,在创建新对象时自动运行。它初始化属性值并将对象设置为有效的起始状态。Python 使用 __init__,而 Java 使用与类同名且没有返回类型的方法。
Example in Python: def __init__(self, model, year): sets self.model = model and self.year = year. Example in Java: public Car(String model, int year) { this.model = model; this.year = year; }. A class can have both a default constructor and parameterised constructors.
Python 示例:def __init__(self, model, year): 设置 self.model = model 和 self.year = year。Java 示例:public Car(String model, int year) { this.model = model; this.year = year; }。一个类可以同时具有默认构造函数和带参数的构造函数。
5. Encapsulation and Access Modifiers | 封装与访问修饰符
Encapsulation means hiding the internal details of an object and exposing only a controlled interface. This protects data from accidental corruption and allows the internal implementation to change without affecting other code. In Java, access modifiers such as private, public and protected enforce encapsulation.
封装意味着隐藏对象的内部细节,只暴露受控接口。这可以保护数据不被意外破坏,并允许在不影响其他代码的情况下更改内部实现。在 Java 中,private、public 和 protected 等访问修饰符强制执行封装。
| Modifier | Same class | Subclass | Other classes |
|---|---|---|---|
| private | Yes | No | No |
| public | Yes | Yes | Yes |
| protected | Yes | Yes | No |
In Python, encapsulation is achieved by convention: attributes starting with a single underscore _x are treated as protected, while double underscore __x triggers name mangling to make accidental access harder. Getters and setters are used to provide controlled access.
在 Python 中,封装通过约定实现:以单下划线 _x 开头的属性被视为受保护,而双下划线 __x 会触发名称改写,使意外访问更困难。使用 getter 和 setter 提供受控访问。
6. Inheritance and Method Overriding | 继承与方法重写
Inheritance allows a new class, called a subclass, to acquire the attributes and methods of an existing class, called a superclass. The subclass can add new features or replace inherited methods through overriding. This supports code reuse and the modelling of hierarchical relationships.
继承允许新类(子类)获取现有类(父类)的属性和方法。子类可以添加新功能或通过重写替换继承的方法。这支持代码复用和层次关系建模。
Method overriding occurs when a subclass defines a method with the same name and parameter list as a method in the superclass. At runtime, the version in the subclass is called for subclass objects. In Python, this is automatic; in Java, the @Override annotation is recommended to catch errors.
方法重写发生在子类定义与父类方法具有相同名称和参数列表的方法时。在运行时,对于子类对象将调用子类中的版本。在 Python 中这是自动的;在 Java 中,建议使用 @Override 注解来捕获错误。
7. Polymorphism | 多态
Polymorphism means “many forms”. It allows the same method call to behave differently depending on the actual object type. In OOP, runtime polymorphism is achieved through method overriding and dynamic dispatch. Compile-time polymorphism is achieved through method overloading in Java.
多态意为“多种形态”。它允许相同的方法调用根据实际对象类型表现出不同的行为。在 OOP 中,运行时多态通过方法重写和动态分派实现。在 Java 中,编译时多态通过方法重载实现。
Example: a superclass variable can refer to subclass objects. Calling animal.speak() might print “Woof” for a Dog object and “Meow” for a Cat object, because each subclass overrides the speak() method.
示例:父类变量可以引用子类对象。调用 animal.speak() 对于 Dog 对象可能输出 “Woof”,对于 Cat 对象可能输出 “Meow”,因为每个子类都重写了 speak() 方法。
| Feature | Overloading | Overriding |
|---|---|---|
| When | Same class | Inheritance hierarchy |
| Signature | Different parameter lists | Same parameter list |
| Binding | Compile-time | Run-time |
8. Abstract Classes and Interfaces | 抽象类与接口
An abstract class is a class that cannot be instantiated. It may contain abstract methods that have no implementation, as well as concrete methods. Subclasses must implement all abstract methods unless they are also abstract. In Java, the abstract keyword declares an abstract class or method. In Python, the abc module provides ABC and @abstractmethod.
抽象类是不能被实例化的类。它可以包含没有实现的抽象方法,也可以包含具体方法。子类必须实现所有抽象方法,除非子类也是抽象的。在 Java 中,abstract 关键字声明抽象类或抽象方法。在 Python 中,abc 模块提供 ABC 和 @abstractmethod。
An interface defines a contract of method signatures without any implementation. A class can implement multiple interfaces in Java, providing flexibility beyond single inheritance. Python uses abstract base classes or protocol classes to achieve similar designs.
接口定义了一组没有实现的方法签名的契约。在 Java 中,一个类可以实现多个接口,这提供了比单继承更大的灵活性。Python 使用抽象基类或协议类来实现类似的设计。
- Abstract class: can have state (attributes) and implemented methods; single inheritance in Java. | 抽象类:可以有状态(属性)和已实现的方法;Java 中是单继承。
- Interface: only method signatures; supports multiple implementation. | 接口:只有方法签名;支持多重实现。
- Use abstract class when sharing state and behaviour; use interface when defining capabilities only. | 当共享状态和行为时使用抽象类;当仅定义能力时使用接口。
9. Code Examples in Python and Java | Python 与 Java 代码示例
The following illustrative snippets show a base class Animal and a subclass Dog. Notice how inheritance, overriding, encapsulation and polymorphism work together.
以下示例片段显示基类 Animal 和子类 Dog。注意继承、重写、封装和多态如何协同工作。
Python:
class Animal: def __init__(self, name): self._name = name def speak(self): return "Some sound"class Dog(Animal): def speak(self): return "Woof"
Java:
class Animal { private String name; public Animal(String name) { this.name = name; } public String speak() { return "Some sound"; }}class Dog extends Animal { public Dog(String name) { super(name); } @Override public String speak() { return "Woof"; }}
These examples demonstrate that Dog inherits the name attribute while overriding the speak() method. A call through an Animal reference to a Dog object will use the overridden method.
这些示例表明 Dog 继承了 name 属性,同时重写了 speak() 方法。通过 Animal 引用调用 Dog 对象时,将使用重写后的方法。
10. Common Exam Mistakes and Tips | 常见考试错误与备考技巧
Edexcel questions on OOP often ask students to distinguish between a class and an object, explain encapsulation, describe inheritance, or identify errors in code. Here are the most common mistakes and how to avoid them.
Edexcel 关于 OOP 的题目经常要求学生区分类与对象、解释封装、描述继承,或找出代码中的错误。以下是最常见的错误以及如何避免它们。
- Confusing class and object: a class is the blueprint, an object is the instance created from it. | 混淆类与对象:类是蓝图,对象是从类创建的实例。
- Forgetting
selfin Python methods or usingthisincorrectly in Java. | 忘记 Python 方法中的self,或在 Java 中错误使用this。 - Stating that private attributes can be accessed directly from outside the class. Private means not accessible outside the class. | 声称私有属性可以从类外部直接访问。私有意味着类外不可访问。
- Mixing up overloading and overriding: overloading changes parameters; overriding keeps the same signature and occurs between parent and child classes. | 混淆重载与重写:重载改变参数;重写保持相同签名,发生在父类和子类之间。
- Failing to call
super()when the parent constructor is needed, causing incomplete initialisation. | 当需要父类构造函数时未调用super(),导致初始化不完整。 - Thinking polymorphism only means inheritance. Polymorphism is about one interface, many implementations. | 认为多态仅指继承。多态是指一个接口,多种实现。
When writing an answer, give a clear definition and then a short example. Use technical vocabulary such as instantiation, encapsulation, override, dynamic dispatch and abstract class. This shows the examiner you understand the concepts rather than just remembering keywords.
作答时,先给出清晰的定义,然后给出简短示例。使用技术词汇,例如实例化、封装、重写、动态分派和抽象类。这向考官表明你理解了概念,而不仅仅是记住关键词。
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