Notes - Object-oriented Programming (OOP) - ver1-part1
Draft discussed and generated with ChatGPT, then edited through personal understanding.
This article is intended as a learning record.
Referencing Object-oriented programming - Wikipedia and related pages.
Preface
The purpose of programming is to solve needs (what problem is being solved and how to solve it). Needs can be fulfilled through a series of functions.
However, designing purely by functions leads to the problem of managing the 「Context (semantic context or scenario)」, which includes scene and environment information.
For example: To operate an air conditioner using a remote, the functions are: Power On ⇨ Adjust Temperature ⇨ Adjust Airflow Direction. You could split these into three separate remotes, but shared data such as "air conditioning mode" would need synchronization.
When multiple groups of functions are involved, the drawbacks of this approach become more significant.
From the perspective of 「semantic context」, using Object-oriented programming can address this issue.
Through 「semantic(meaning)」, related functions and contextual data are encapsulated within an object, giving each object a clear responsibility so that functionality aligns with 「semantic(meaning)」.
Overview
🎯 Analogy
You have a pen in hand — the pen is Object.
“Using a blue ballpoint pen to take notes” is an 「action (method)」, and how much ink remains is the 「state (data)」. The specification of a pen with “blue ink, ballpoint, able to write notes” represents Class.
📘 Explanation
- A real-world 「thing」 is an Object, which has a 「lifecycle」.
- By extracting the characteristics of a 「thing」 from a 「need (what problem it solves and how)」, a set of related traits — the specification — forms a Class, which has no 「lifecycle」.
- Object-oriented programming is a way of designing programs with Object as the core, emphasizing simulation, abstraction, and modular thinking.
- Class contains both 「state (data)」 and 「behavior logic (methods)」, integrating them to describe roles, behaviors, interactions, and semantic context.
- Through Class, one can create Object with lifecycle.
- Through numerous specifications, complex systems such as a 'scientific calculator' can be constructed.
- This approach can be applied to programming to plan and analyze needs, designing correlated behaviors, well-defined responsibilities, roles, and minimally bounded elements.
Model Thinking
- Convert needs into a 「structured model」 that solves problems.
- Often centered around 「semantic (business semantic)」, with all 「participants」 sharing a consistent definition of the 「semantic(meaning)」.
- Sometimes, a simple semantic concept can be divided into multiple collaborating modules, each module containing multiple collaborating classes — e.g., "calendar", "user", "protection mechanism".
- Applicable to various modeling approaches: analysis, design, implementation, with iterative refinement prioritized toward building a minimal functional system; e.g., divide and conquer — break down large problems into composable smaller ones and implement each.
Simulating Real-world Objects
🎯 Analogy
A car simulator doesn’t need to build a full car; it uses simulation. A button starts the engine, a steering wheel turns wheels, the accelerator affects engine power. The modules collaborate to replicate real car behavior.
📘 Explanation
- Define models via Class to simulate real-world object characteristics and behaviors.
- Some objects are data-oriented, like 'Form'; some are behavior-oriented, like 'Tool'.
Simulating Concepts
🎯 Analogy
In a company, there are roles such as accountants, sales specialists, and engineers. Each role has responsibilities and characteristics.
Within a 「context」, only 「certain characteristics」 are shown.
📘 Explanation
- Use models to describe units and roles within a system — the system may contain multiple 「scenarios」.
- Class corresponds to conceptual roles and their behaviors.
- A concept is usually not a full system, but part of a core module.
Structure, Modularity, Maintainability, Reusability
🎯 Analogy
Using many building blocks allows assembly, disassembly, and replacement, unlike a single solid block. It is more maintainable and easier to refactor.
📘 Explanation
- Break down large systems into small modules, reusable across scenarios. This increases efficiency in maintenance, debugging, testing, and expansion.
1. Definitions and Characteristics
1. Class and Object
- Class: A template for Object, defining 「data (state)」 and 「methods (behavior logic)」, a type of Type.
- Object: An Instance of Class, with 「lifecycle」 and individual 「state」.
- 🎯 Analogy: A recipe says 'prepare 150ml of water' — this conceptual water is Class; in actual cooking, the water you pour is Object, possibly alkaline due to minerals.
2. Interface and Abstract Class
-
Interface: A fully abstract Type, typically containing no implementation. It defines 「public method contracts (names, input, output)」 and 「public properties (names, data)」. A Class must implement these definitions to 「declare implementation」 of the Interface. It emphasizes 「capability」 and 「role」, not 「state (data)」.
- 🎯 Analogy: When choosing a computer, you consider what each port supports — charging, connecting to a phone, etc. A port may support multiple functions. These 「functional capabilities」 represent Interface.
-
Abstract Class: Serves as a common base for other Class, defining shared interfaces and default logic. It can include 「abstract methods (no implementation)」 and 「concrete methods (with implementation)」.
- 🎯 Analogy: Define 'Animal' as an abstract concept. 'Dog' and 'Cat' derive from it. Both can perform a sound (abstract method), but the implementation differs (bark, meow). Shared behavior like drinking water (with parameters) is a concrete method. 'Animal' can be an Abstract Class while 'Dog' and 'Cat' are Class.
2. Four Core Features (Four Pillars)
Abstraction
🎯 Analogy
A driver uses the 'accelerator' and 'brake' to control speed without knowing engine internals. Even if tires are changed, 'accelerator and brake' still work.
📘 Explanation
- Abstraction extracts general concepts from concrete details, focusing 「attention」 on the current goal.
- Provides functions while hiding implementation; replacing implementation should not affect function.
- Behavior is defined using Interface or Abstract Class — abstract portions do not provide implementation.
- Low coupling improves module flexibility.
Encapsulation
🎯 Analogy
Using a computer case to operate a computer provides 'normal', guaranteed usage (Encapsulation). Directly manipulating the motherboard may enable more operations, but can break 'normal functions' — violating encapsulation.
📘 Explanation
- Data and methods are enclosed within a single unit, hiding internal structures or implementation details.
- Ensures 「valid state (data consistency)」.
- Use private to restrict external access and public methods for necessary operations.
- Encapsulation shares some concepts with abstraction, but focuses more on protecting internal state and preventing unnecessary coupling.
- Be cautious of coupling issues via Inheritance.
Inheritance
🎯 Analogy
If 'dogs and cats are types of animals', then 'dog' and 'cat' should have all characteristics defined by 'animal'. This acquisition of traits is Inheritance.
📘 Explanation
- Inheritance usually reflects an is-a relationship — e.g., 'a cat is an animal'.
- It derives derived class from base class.
- The derived class automatically inherits all attributes and methods from base class, enabling logic reuse and conceptual hierarchy.
- derived class may add or override functions, but the base class must plan overriding strategies to avoid breaking Encapsulation or adding coupling.
- Evaluate whether Inheritance is reasonable and necessary — poor structures cause confusion, and structure must reflect 「semantic(meaning)」.
- In general development, Composition is preferred over Inheritance — using attributes or parameters rather than forcing inheritance.
- Use Inheritance only when there is a clear 「semantic(meaning)」 hierarchy; otherwise, use Composition.
Polymorphism
- The same operation may behave differently across types.
- There are various forms of polymorphism with different focuses.
Subtyping
🎯 Analogy
There are many types of 'mail' — 'registered mail', 'express mail'. At the post office counter, all can be processed for sending, though actual actions differ. 'Mail' is the base class, while 'registered mail' and 'express mail' are derived class.
📘 Explanation
- An operation applicable to the base class can also apply to its derived class, yielding different behaviors, while maintaining the same expected effect.
Parametric polymorphism
🎯 Analogy
You expect to perform a 'storage action' using a 'container'. The 'container' may be a 'storage box' or a 'cabinet'. For the action, you focus only on the 'container' as a concept.
📘 Explanation
- Replace Class with a 「variable」, focusing on what 「actions」 the 「variable」 can perform — the 「variable」 may represent an Interface.
- In Object-oriented programming, this is known as Generics, enhancing code reuse.
Ad hoc polymorphism
🎯 Analogy
A 'unlock' function may use a 'key', 'fingerprint', or 'password' as input. Same action name, different inputs.
📘 Explanation
Methods with the same name but different implementations based on 「input parameters」, maintaining the same expected effect. Includes:
Function overloading: Same method name within one Class but different parameter lists.
Operator overloading: Redefine operators like '+', '=='. Can cause confusion, e.g., mixing numeric addition and string concatenation in one 「expression」.
Object relationships will be covered in the next note.
Thanks for reading!