📚 Object-Oriented Programming Skills (OPS) | 面向对象编程技能
Object-oriented programming (OOP) forms the backbone of most modern software development, and Edexcel A-Level Computer Science requires you to master its core skills. This article guides you through the essential OOP concepts — from classes and objects to inheritance and polymorphism — explaining how each principle helps create more scalable, maintainable and robust code.
面向对象编程(OOP)是现代软件开发的基础,Edexcel A-Level 计算机科学考试要求你掌握其核心技能。本文将带你深入理解从类与对象到继承与多态等重要 OOP 概念,并解释每个原则如何帮助构建更具扩展性、可维护性和健壮性的代码。
1. Classes and Objects | 类与对象
A class is a blueprint that defines the attributes (data) and methods (behaviours) that objects created from it will possess. An object is a concrete instance of a class, with its own unique state stored in fields.
类是定义属性和方法的蓝图,对象则是根据类创建的具体实例,拥有存储在字段中的独立状态。
-
A class declaration in Java typically includes field declarations, a constructor, and method definitions. For example, a
Carclass might have fields likeString modelandint speed, along with methodsaccelerate()andbrake().Java 中的类声明通常包含字段声明、构造方法和普通方法定义。例如,一个
Car类可能拥有String model和int speed字段,以及accelerate()和brake()方法。 -
An object is created using the
newkeyword, which calls the constructor to initialise the object’s state:Car myCar = new Car("Tesla");. Each object maintains its own copy of instance fields.对象通过
new关键字创建,并调用构造方法进行初始化:Car myCar = new Car("Tesla");。每个对象都拥有实例字段的独立副本。
2. Encapsulation and Information Hiding | 封装与信息隐藏
Encapsulation bundles data and the methods that operate on that data within a single unit (the class), and restricts direct access to an object’s internal state. This is achieved through access modifiers such as private, public, and protected.
封装将数据和操作数据的方法打包在一个单元(类)内,并限制对对象内部状态的直接访问。这通过 private、public 和 protected 等访问修饰符来实现。
-
Marking fields as
privateprevents external classes from modifying them arbitrarily. Instead, controlled access is provided via public getter and setter methods, allowing validation or transformation logic to be applied.将字段标记为
private可以防止外部类随意修改它们。取而代之的是通过公有的 getter 和 setter 方法提供受控访问,从而可以施加验证或转换逻辑。 -
Encapsulation reduces coupling between components and makes it easier to change the internal implementation without affecting client code. For instance, you could change how a
balanceis stored in aBankAccountclass without altering thewithdraw()method’s public signature.封装降低了组件之间的耦合度,使得在不影响客户端代码的情况下更改内部实现变得更加容易。例如,可以改变
BankAccount类中balance的存储方式,而无需修改withdraw()方法的公共签名。
3. Constructors and Instantiation | 构造方法与实例化
A constructor is a special method automatically invoked when an object is created. It typically initialises fields and sets up the object’s initial state. A class can have multiple overloaded constructors with different parameter lists.
构造方法是在创建对象时自动调用的特殊方法,通常用于初始化字段并设定对象的初始状态。一个类可以有多个具有不同参数列表的重载构造方法。
-
A default constructor with no parameters is provided by the compiler only if no other constructor is explicitly defined. Once you define any constructor, you must explicitly add a no-arg constructor if it is needed.
只有在没有显式定义任何构造方法时,编译器才会提供无参的默认构造方法。一旦定义了构造方法,如果还需要无参构造方法,就必须显式添加。
-
Constructor chaining can be used inside a class to avoid code duplication, using
this()to call another constructor of the same class. Overridden constructors in subclasses call the superclass constructor viasuper().在类内部可以通过
this()调用同一个类的另一个构造方法,实现构造方法链,从而避免代码重复。子类的构造方法通过super()调用父类的构造方法。
4. Inheritance and the ‘Is-a’ Relationship | 继承与“是一个”关系
Inheritance allows a class (subclass) to acquire the properties and behaviours of another class (superclass). This models an ‘is-a’ relationship, promoting code reuse and the creation of hierarchical class structures.
继承允许一个类(子类)获取另一个类(超类)的属性和行为,它模型化了“是一个”关系,促进了代码复用以及层次化类结构的构建。
-
In Java, the
extendskeyword establishes inheritance. A subclass can override superclass methods to provide specialised behaviour while still being able to call the superclass version viasuper.methodName().在 Java 中,使用
extends关键字建立继承关系。子类可以重写超类的方法以提供特化行为,同时仍然可以通过super.methodName()调用超类的版本。 -
Inheritance should only be used when the subclass genuinely passes the ‘is-a’ test (e.g. a
Dogis anAnimal). Misusing inheritance for mere code sharing can lead to fragile designs; the ‘has-a’ relationship (composition) is often a better alternative.只有当子类真正通过“是一个”测试(例如狗是一种动物)时,才应使用继承。仅仅为了共享代码而滥用继承可能导致脆弱的设计;“有一个”关系(组合)通常是更好的选择。
5. Method Overriding and Polymorphism | 方法重写与多态
Polymorphism means ‘many forms’ and allows objects of different classes to be treated as objects of a common superclass. The actual method executed is determined at runtime based on the object’s type, enabling dynamic binding.
多态意为“多种形态”,它允许将不同类的对象视为同一个公共超类的对象来处理。实际执行的方法在运行时根据对象的类型决定,从而实现动态绑定。
-
A superclass reference can point to a subclass object:
Animal a = new Dog();. When callinga.speak(), the JVM executes the overriddenspeak()method inDog, not the one inAnimal. This is late binding.超类引用可以指向子类对象:
Animal a = new Dog();。调用a.speak()时,JVM 执行的是Dog中重写的speak()方法,而非Animal中的。这就是动态绑定。 -
The
@Overrideannotation helps the compiler check that a method is properly overriding a superclass method. Overriding requires the same method signature and a return type that is covariant (the same or a subtype).@Override注解有助于编译器检查方法是否正确重写了超类方法。重写要求具有相同的方法签名,且返回类型是协变的(相同或子类型)。
6. Abstract Classes and Methods | 抽象类与抽象方法
An abstract class cannot be instantiated directly and is designed to serve as a base class for other classes. It may contain abstract methods (without a body) that force concrete subclasses to provide an implementation.
抽象类不能直接实例化,其设计目的是作为其他类的基类。它可以包含抽象方法(没有方法体),强制具体子类提供实现。
-
In UML and Java, abstract classes are declared with the
abstractkeyword. Any class with at least one abstract method must itself be declared abstract. This enforces a contract that all subclasses implement the essential behaviour.在 UML 和 Java 中,抽象类用
abstract关键字声明。任何包含至少一个抽象方法的类本身也必须声明为抽象类。这强制所有子类实现必要的行为,形成一种契约。 -
Abstract classes can also provide concrete methods and constructors, which are inherited by subclasses. This reduces code duplication while still demanding that certain critical methods are customised.
抽象类也可以提供具体方法和构造方法,这些会被子类继承。这减少了代码重复,同时又要求某些关键方法被自定义。
7. Interfaces and Polymorphic Behaviour | 接口与多态行为
An interface defines a set of method signatures (a protocol) that implementing classes must fulfil. Unlike abstract classes, interfaces represent a pure contract; in Java, a class can implement multiple interfaces, achieving a form of multiple inheritance of behaviour.
接口定义了一组方法签名(协议),由实现类来履行。与抽象类不同,接口代表纯契约;在 Java 中,一个类可以实现多个接口,从而实现行为上的多重继承。
-
Interfaces promote loose coupling. For instance, a
Sortableinterface with acompareTo()method enables any class that implements it to be sorted by a general-purpose sorting algorithm. The algorithm depends only on the interface, not on concrete classes.接口促进了松耦合。例如,拥有
compareTo()方法的Sortable接口可以使任何实现它的类被通用排序算法排序。该算法仅依赖于接口,而不依赖于具体类。 -
Since Java 8, interfaces can include default methods with a body, allowing evolvable APIs without breaking existing implementations. Still, the core purpose remains defining what a class can do, rather than what a class is.
自 Java 8 起,接口可以包含带有方法体的默认方法,使得 API 能够演变而不破坏现有实现。尽管如此,接口的核心目的仍然是定义类能做什么,而非类是什么。
8. Composition and Aggregation | 组合与聚合
Composition and aggregation are ‘has-a’ relationships that allow complex classes to be built by assembling simpler objects. Composition implies ownership and a lifetime dependency; aggregation implies a weaker relationship where parts can exist independently.
组合与聚合是“有一个”关系,允许通过组装较简单的对象来构建复杂类。组合意味着所有权和生命周期依赖;聚合则表示一种更弱的关系,部分可以独立存在。
-
In composition, if the whole object is destroyed, its parts are also destroyed. For example, a
Houseobject might be composed ofRoomobjects that have no meaning outside the house. Code typically instantiates the parts inside the whole class.在组合关系中,如果整体对象被销毁,其部分也会被销毁。例如,一个
House对象可能由Room对象组成,后者在房子之外没有意义。代码通常在整体类内部实例化组成部分。 -
Aggregation uses references to objects that are created elsewhere. A
Universityobject has a list ofStudentobjects, but students continue to exist even if the university object is deleted. This models real-world associations more loosely.聚合使用对其他地方创建的对象的引用。一个
University对象拥有一个Student对象的列表,但即使大学对象被删除,学生对象仍然存在。这以更松散的方式对现实世界的关联进行建模。
9. Access Modifiers and Visibility | 访问修饰符与可见性
Access modifiers define the scope at which class members can be used. The four levels — private, default (package-private), protected, and public — control encapsulation and protect the integrity of the object’s data.
访问修饰符定义了类成员可被使用的范围。四个级别——private、默认(包私有)、protected 和 public——控制了封装并保护对象数据的完整性。
private → only within the same class | 仅同一类内default → same package | 同一包内protected → same package + subclasses | 同一包及子类public → everywhere | 任何地方
Careful use of these modifiers is critical; overexposing internal fields as public breaks encapsulation, while making methods unnecessarily private hinders extensibility. The ‘most restrictive adequate’ principle is a good rule of thumb.
谨慎使用这些修饰符至关重要;将内部字段过度暴露为 public 会破坏封装,而不必要地将方法设为 private 又会阻碍扩展性。“在足够的条件下尽可能严格”是一个很好的经验法则。
10. Static vs Instance Members | 静态与实例成员
Static members (fields and methods) belong to the class itself rather than to any particular object. They are shared across all instances and can be accessed without creating an object. Instance members, conversely, require an object context.
静态成员(字段和方法)属于类本身,而不属于任何特定对象。它们在所有实例之间共享,无需创建对象即可访问。相反地,实例成员需要对象上下文。
-
A common use of static fields is to hold constants (e.g.
Math.PI) or to keep track of shared data such as a count of instances created. Static methods are often utility functions (e.g.Math.sqrt()) that do not depend on object state.静态字段的常见用途包括保存常量(如
Math.PI)或跟踪共享数据,例如已创建实例的计数。静态方法通常是实用函数(如Math.sqrt()),不依赖于对象状态。 -
Static methods cannot directly access instance fields or call instance methods because they have no implicit
thisreference. Understanding this distinction is essential for designing well-structured OOP programs.静态方法不能直接访问实例字段或调用实例方法,因为它们没有隐式的
this引用。理解这一区别对设计结构良好的 OOP 程序至关重要。
11. Design Principles: SOLID Basics | 设计原则:SOLID 基础
SOLID is an acronym for five design principles that help produce more understandable, flexible, and maintainable object-oriented systems. Edexcel expects you to appreciate how good design reduces coupling and increases cohesion.
SOLID 是五个设计原则的首字母缩写,有助于产生更易理解、更灵活且更易于维护的面向对象系统。Edexcel 希望你理解好的设计如何降低耦合度并提高内聚性。
S — Single Responsibility | 单一职责
O — Open/Closed | 开闭原则
L — Liskov Substitution | 里氏替换
I — Interface Segregation | 接口隔离
D — Dependency Inversion | 依赖倒置
-
For instance, the Single Responsibility Principle states that a class should have only one reason to change. Splitting a
Reportclass intoReportDataandReportPrinterseparates data handling from formatting.例如,单一职责原则指出一个类应当只有一个引起变化的原因。将
Report类拆分为ReportData和ReportPrinter就把数据处理与格式分离了开来。 -
The Open/Closed Principle encourages classes to be open for extension but closed for modification. This is often achieved through polymorphism and interfaces, allowing new behaviours to be added via new classes rather than altering existing code.
开闭原则鼓励类对扩展开放,对修改封闭。这通常通过多态和接口来实现,允许通过新类添加新行为,而不是修改现有代码。
12. Testing and Debugging OOP Code | 测试与调试 OOP 代码
Testing object-oriented programs involves unit testing individual classes, integration testing interactions between objects, and using debugging tools to inspect object state at runtime. Proper encapsulation aids testing by isolating units.
测试面向对象程序包括对各个类进行单元测试、对对象之间的交互进行集成测试,以及使用调试工具检查运行时的对象状态。恰当的封装通过隔离各个单元来帮助测试。
-
Use assertions to verify that objects maintain valid states after method calls. For example, after calling
withdraw(50)on an account with initial balance 200, assert thatgetBalance()returns 150 and that the object still respects its invariants.使用断言来验证对象在方法调用后保持了有效状态。例如,在对初始余额为 200 的账户调用
withdraw(50)后,断言getBalance()返回 150,并且对象仍然遵守其不变条件。 -
Polymorphism can complicate tracing because a method call might execute any of several implementations. Using breakpoints in an IDE and logging the actual runtime class of an object help diagnose such problems effectively.
多态可能使追踪变得复杂,因为一个方法调用可能执行几种实现中的任何一种。在 IDE 中使用断点并记录对象的实际运行时类有助于有效地诊断此类问题。
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课程辅导,国外大学本科硕士研究生博士课程论文辅导Cancel reply