Back to series
· 11 min read

Encapsulation, Inheritance & Polymorphism


1. The Three Core Characteristics of Object-Oriented Programming

Object-Oriented Programming (OOP) organizes data and behavior through objects. Among its features, encapsulation, inheritance, and polymorphism are the three most representative core characteristics.

Core Characteristic English Name Main Problem Solved
Encapsulation Encapsulation How to protect an object's internal state and control external access
Inheritance Inheritance How to reuse the attributes and behavior of existing types
Polymorphism Polymorphism How to implement different behaviors through a unified interface

The three are related to some extent, but they solve different problems:

  • Encapsulation focuses on the boundary between an object's internal implementation and its external interface.
  • Inheritance focuses on relationships between types and code reuse.
  • Polymorphism focuses on differences in behavior of the same interface across different objects.
flowchart TB
    A["Object-Oriented Programming (OOP)"]
    B["Encapsulation"]
    C["Inheritance"]
    D["Polymorphism"]

    A --> B
    A --> C
    A --> D

    B --> E["Protect internal state<br/>Control access boundary"]
    C --> F["Establish type relationships<br/>Reuse existing implementations"]
    D --> G["Unified interface<br/>Dynamically dispatch behavior"]

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style E fill:#E8EDF2,stroke:#B8C3CE,color:#334155
    style F fill:#E8EDF2,stroke:#B8C3CE,color:#334155
    style G fill:#E8EDF2,stroke:#B8C3CE,color:#334155
    linkStyle default stroke:#A3B8AC,stroke-width:1.5px

2. Encapsulation

2.1 What Is Encapsulation?

Encapsulation organizes data and the behaviors that operate on that data within the same object or module, and provides controlled access to the outside through interfaces.

The core goal of encapsulation is not simply to hide variables, but to:

  1. Hide internal implementation details.
  2. Restrict direct modification of internal state from outside.
  3. Maintain data consistency through public interfaces.
  4. Reduce coupling between modules.
  5. Allow internal implementations to change while minimizing impact on external callers.

For example, a bank account contains a balance, an account holder, and deposit and withdrawal operations.

If the balance can be modified arbitrarily, it is difficult to ensure the validity of the account state.

A design that is not recommended:

class Account:
    def __init__(self, balance):
        self.balance = balance


account = Account(1000)

account.balance = -5000

External code can directly modify the balance to a negative number, bypassing business rules.

Using encapsulation:

class Account:
    def __init__(self, balance):
        if balance < 0:
            raise ValueError("初始余额不能为负数")

        self.__balance = balance

    def deposit(self, amount):
        if amount <= 0:
            raise ValueError("存款金额必须大于零")

        self.__balance += amount

    def withdraw(self, amount):
        if amount <= 0:
            raise ValueError("取款金额必须大于零")

        if amount > self.__balance:
            raise ValueError("余额不足")

        self.__balance -= amount

    def get_balance(self):
        return self.__balance

Usage:

account = Account(1000)

account.deposit(500)
account.withdraw(200)

print(account.get_balance())  # 1300

External code modifies the balance through deposit() and withdraw(), and the account object is responsible for maintaining its own state.

2.2 Access Control

Access control specifies which code can access class members.

Languages such as Java and C++ usually provide explicit access modifiers.

Modifier Access scope Description
public Open access Allows external access
protected Protected access Typically allows access by subclasses and specific scopes
private Private access Restricted to access within the class
Default access level Depends on the language For example, package-level access in Java

Java example:

public class Account {
    private double balance;

    public Account(double balance) {
        if (balance < 0) {
            throw new IllegalArgumentException("余额不能为负数");
        }

        this.balance = balance;
    }

    public void deposit(double amount) {
        if (amount <= 0) {
            throw new IllegalArgumentException("金额必须大于零");
        }

        balance += amount;
    }

    public double getBalance() {
        return balance;
    }
}

Among them:

  • balance is a private field.
  • deposit() is a public operation interface.
  • getBalance() provides controlled data reading capability.

Note that the specific access rules of protected vary by language. For example, protected in Java also involves package access rules, so it cannot be simply equated with subclass accessibility in all languages.

2.3 Encapsulation Mechanisms in Different Languages

Encapsulation is a design idea, and different languages provide different implementation mechanisms.

Language Common implementation methods
Java private, protected, public
C++ private, protected, public
Python Naming conventions, name mangling, property accessors
JavaScript #private private fields, closures
Go Export controlled by the capitalization of the identifier's first letter
Rust Module visibility, pub

For example, Python:

class User:
    def __init__(self, name):
        self._name = name
        self.__password = "secret"

    @property
    def name(self):
        return self._name

Here:

  • _name indicates a conventionally non-public attribute.
  • __password triggers the name mangling mechanism.
  • @property allows methods to be called through property access syntax.

Python's double underscore is not equivalent to Java's strict private. It primarily reduces the risk of accidental access and subclass naming conflicts through name mangling.

2.4 Encapsulation and Data Integrity

The value of encapsulation is not only hiding fields; more importantly, it makes objects responsible for maintaining their own invariants.

An invariant is a condition that an object must satisfy throughout its valid lifecycle.

For example, an account balance cannot be negative:

balance \geq 0

Every time the balance is modified, this constraint must be satisfied.

flowchart TB
    A["External business code"]
    B["Call public method"]
    C["Check input parameters"]
    D{"Does it meet business constraints?"}
    E["Reject operation"]
    F["Modify internal state"]
    G["Maintain object invariants"]

    A --> B
    B --> C
    C --> D
    D -->|"No"| E
    D -->|"Yes"| F
    F --> G

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style C fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style D fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style E fill:#FBE9E9,stroke:#D9AAAA,color:#334155
    style F fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style G fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    linkStyle default stroke:#A3B8AC,stroke-width:1.5px

In actual development, encapsulation is usually combined with the following design principles:

  • Centralize state modification into explicit operation interfaces.
  • Validate parameters at interface entry.
  • Avoid exposing internal collections that can be modified arbitrarily.
  • Add synchronization protection for shared state accessed concurrently.
  • Keep objects in a valid state at all times, and avoid partial initialization or the propagation of invalid states.

2.5 Encapsulation Is Not Complete Hiding

Encapsulation does not mean that all fields must be private, nor does it mean that object properties cannot be exposed publicly.

For example, a read-only configuration object can expose immutable properties without writing getters and setters for every field.

What really matters is which operations external code can perform and whether those operations violate object constraints.

Blindly adding getters and setters may merely wrap field access in an extra layer without truly achieving effective encapsulation.

3. Inheritance

3.1 What Is Inheritance

Inheritance is a mechanism for establishing type hierarchy relationships, allowing one type to extend the properties and behavior of another type.

The class being inherited from is called:

  • Parent class
  • Base class
  • Superclass

A type that inherits from another class is called:

  • Child class
  • Derived class
  • Subtype (the exact meaning depends on the type system)

For example, if the system has a general Animal class, you can further define Dog and Cat.

class Animal:
    def eat(self):
        print("动物正在进食")


class Dog(Animal):
    def bark(self):
        print("汪汪")


class Cat(Animal):
    def meow(self):
        print("喵喵")


dog = Dog()
dog.eat()
dog.bark()

cat = Cat()
cat.eat()
cat.meow()

Dog and Cat inherit the eat() method of Animal while having their own behaviors.

3.2 Basic Structure of Inheritance

flowchart TB
    A["Animal<br/>Parent class"]
    B["Dog<br/>Subclass"]
    C["Cat<br/>Subclass"]
    D["Bird<br/>Subclass"]

    A --> B
    A --> C
    A --> D

    B --> E["bark()"]
    C --> F["meow()"]
    D --> G["fly()"]

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style C fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style D fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style E fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style F fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style G fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    linkStyle default stroke:#A3B8AC,stroke-width:1.5px

Inheritance mainly manifests in two aspects:

  1. A subclass can reuse members of the parent class that are allowed to be inherited.
  2. A subclass can extend its own properties and methods, or redefine inherited methods.

3.3 Method Overriding

Method overriding is when a subclass provides a new implementation for a method already defined in the parent class.

class Animal:
    def speak(self):
        print("动物发出声音")


class Dog(Animal):
    def speak(self):
        print("汪汪")


class Cat(Animal):
    def speak(self):
        print("喵喵")

At this point:

dog = Dog()
cat = Cat()

dog.speak()  # Woof
cat.speak()  # Meow

After a subclass overrides a parent class method, when that method is called, the corresponding implementation is selected based on the actual object type.

This is also an important foundation for runtime polymorphism.

Note that method overriding and method overloading are not the same concept:

Comparison Method Overriding Method Overloading
English Overriding Overloading
Main purpose Change the implementation of an inherited method Provide calls with different parameter forms
Depends on inheritance Usually depends on inheritance or interface implementation relationships Not necessarily
Typical manifestation Subclass reimplements a parent class method Methods with the same name have different parameter lists
Common languages Java, C++, Python Java, C++

Python does not support compile-time method overloading based on multiple parameter signatures in the traditional sense, but similar effects can be achieved through default parameters, variable arguments, and dispatch mechanisms.

3.4 super: Calling the Parent Class Implementation

Sometimes a subclass needs to call a parent class method before or after extending its own logic.

Python example:

class Animal:
    def __init__(self, name):
        self.name = name

    def speak(self):
        print("动物发出声音")


class Dog(Animal):
    def __init__(self, name, breed):
        super().__init__(name)
        self.breed = breed

    def speak(self):
        super().speak()
        print("汪汪")

super() is used to access the next implementation according to the method resolution order.

In simple single inheritance, it usually means calling the parent class implementation; in Python multiple inheritance, it follows the MRO (Method Resolution Order) and does not simply point to a single fixed parent class.

3.5 Types of Inheritance

Depending on how inheritance relationships are organized, common inheritance types include:

Type Description
Single inheritance A subclass inherits from one direct parent class
Multiple inheritance A subclass inherits from multiple parent classes
Multilevel inheritance The inheritance relationship forms multiple levels
Hierarchical inheritance Multiple subclasses inherit from the same parent class
Hybrid inheritance A combination of multiple inheritance forms

Diagram:

flowchart TB
    A["Base"]
    B["ChildA"]
    C["ChildB"]
    D["ChildC"]
    E["GrandChild"]

    A --> B
    A --> C
    B --> D
    D --> E

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style C fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style D fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style E fill:#FFF5DE,stroke:#E8D29A,color:#334155
    linkStyle default stroke:#A3B8AC,stroke-width:1.5px

Support for multiple inheritance varies across languages:

  • C++ supports multiple inheritance of classes.
  • Python supports multiple inheritance and uses MRO to resolve method lookup order issues.
  • Java classes support only single inheritance but can implement multiple interfaces.
  • C# classes support only single inheritance but support implementing multiple interfaces.
  • Go does not use the traditional class inheritance mechanism; it mainly achieves code reuse and behavior abstraction through composition and interfaces.
  • Rust does not support traditional class inheritance; it achieves similar abstraction capabilities through composition, traits, and generics.

3.6 Multiple Inheritance and the Diamond Inheritance Problem

Multiple inheritance can lead to complex member lookup and initialization issues.

A typical scenario is diamond inheritance:

flowchart TB
    A["Base"]
    B["Left"]
    C["Right"]
    D["Child"]

    A --> B
    A --> C
    B --> D
    C --> D

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
    linkStyle default stroke:#A3B8AC,stroke-width:1.5px

Assume:

  • Left inherits from Base.
  • Right inherits from Base.
  • Child inherits from both Left and Right.

In this case, the following may occur:

  1. There is ambiguity in member lookup for Base.
  2. The initialization logic of Base may be executed multiple times.
  3. Method name conflicts may occur between different parent classes.
  4. There may be multiple base-class subobjects inside the object.

C++ can solve the problem of shared base-class subobjects in specific diamond-inheritance scenarios through virtual inheritance.

Python, by contrast, determines the method lookup order through MRO and, combined with cooperative super() calls, implements initialization cooperation in complex inheritance structures.

Python example:

class A:
    def show(self):
        print("A")


class B(A):
    def show(self):
        print("B")
        super().show()


class C(A):
    def show(self):
        print("C")
        super().show()


class D(B, C):
    def show(self):
        print("D")
        super().show()


obj = D()
obj.show()

print(D.mro())

Output order:

D
B
C
A

The call order here is determined by the method resolution order of D.

3.7 Advantages and Problems of Inheritance

Advantages:

  • Reuse existing code.
  • Establish a clear type hierarchy.
  • Support method overriding and polymorphism.
  • Manage common behavior uniformly.
  • Make it easy to express stable domain type relationships.

Problems:

  • Changes to a parent class may affect multiple subclasses.
  • Overly deep inheritance hierarchies increase the cost of understanding.
  • Subclasses tend to depend on the internal implementation of parent classes.
  • Multiple inheritance may introduce method conflicts and initialization complexity.
  • Inappropriate inheritance breaks the type substitution relationship.

Inheritance should not be used merely to reuse a few lines of code. Inheritance is a sound design only when the subclass truly conforms to the type semantics expressed by the parent class.

4. Polymorphism

4.1 What Is Polymorphism

Polymorphism refers to the ability to operate objects of different types through a unified interface, with each object exhibiting different behavior according to its actual type.

For example, the system defines a unified speak() method:

  • Dog calls speak() and makes a woof sound.
  • Cat calls speak() and makes a meow sound.
  • Bird calls speak() and makes a chirp sound.

The caller does not need to understand the internal implementation of each animal; it only needs to call through the unified interface.

class Animal:
    def speak(self):
        raise NotImplementedError


class Dog(Animal):
    def speak(self):
        print("汪汪")


class Cat(Animal):
    def speak(self):
        print("喵喵")


class Bird(Animal):
    def speak(self):
        print("啾啾")


def make_sound(animal):
    animal.speak()


animals = [
    Dog(),
    Cat(),
    Bird()
]

for animal in animals:
    make_sound(animal)

Output:

汪汪
喵喵
啾啾

make_sound() does not need separate invocation logic for Dog, Cat, and Bird.

4.2 Core Mechanisms of Polymorphism

The key to polymorphism lies in:

  • A unified call interface.
  • Concrete implementations for different types.
  • Selecting the method actually executed based on the type system and dispatch rules.
flowchart TB
    A["Caller"]
    B["Unified interface speak()"]
    C{"Actual object type"}
    D["Dog.speak()"]
    E["Cat.speak()"]
    F["Bird.speak()"]
    G["Execute corresponding behavior"]

    A --> B
    B --> C
    C --> D
    C --> E
    C --> F
    D --> G
    E --> G
    F --> G

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style C fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style D fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style E fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style F fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style G fill:#E8EDF2,stroke:#B8C3CE,color:#334155
    linkStyle default stroke:#A3B8AC,stroke-width:1.5px

Note: the type determination here is a conceptual abstraction. Actual languages may implement polymorphism through virtual method tables, interface dispatch, method lookup, generic monomorphization, or other mechanisms.

4.3 Compile-time Polymorphism and Runtime Polymorphism

Polymorphism can be classified according to when methods or operations are dispatched.

Type English Main characteristics
Compile-time polymorphism Compile-time Polymorphism Determine the specific call or instantiation form at compile time
Runtime polymorphism Runtime Polymorphism Determine specific behavior based on the runtime object type

Compile-time Polymorphism

Compile-time polymorphism usually includes:

  • Function overloading.
  • Operator overloading.
  • Static dispatch of templates and generics.
  • Specific implementations that the compiler can determine at compile time.

C++ function overloading example:

#include <iostream>
#include <string>

void print(int value) {
    std::cout << value << std::endl;
}

void print(const std::string& value) {
    std::cout << value << std::endl;
}

int main() {
    print(100);
    print(std::string("Hello"));
}

The compiler selects the corresponding function version based on the parameter type.

C++ template example:

template <typename T>
T add(T a, T b) {
    return a + b;
}

int main() {
    int result1 = add(1, 2);
    double result2 = add(1.5, 2.5);
}

The compiler generates the corresponding instantiation code based on the template parameters.

Runtime Polymorphism

Runtime polymorphism is usually implemented through inheritance, interfaces, and dynamic dispatch.

Java example:

abstract class Animal {
    public abstract void speak();
}

class Dog extends Animal {
    @Override
    public void speak() {
        System.out.println("汪汪");
    }
}

class Cat extends Animal {
    @Override
    public void speak() {
        System.out.println("喵喵");
    }
}

public class Main {
    public static void main(String[] args) {
        Animal animal = new Dog();
        animal.speak();

        animal = new Cat();
        animal.speak();
    }
}

Although the declared type of the variable animal is always Animal, the method actually executed depends on the type of the object it references.

4.4 Dynamic Binding

Dynamic binding is an important implementation mechanism for runtime polymorphism.

In languages that support dynamic dispatch, the specific implementation of a method call may not be determinable solely from the declared type of the variable; it may need to be selected based on the runtime object type.

For example:

Animal animal = new Dog();
animal.speak();

Here:

  • Animal is the declared type of the variable.
  • Dog is the actual type of the runtime object.
  • The specific implementation of speak() is selected by the dynamic dispatch mechanism.

In C++, only calls that follow the rules of virtual function dynamic dispatch have this behavior.

#include <iostream>

class Animal {
public:
    virtual void speak() {
        std::cout << "Animal" << std::endl;
    }

    virtual ~Animal() = default;
};

class Dog : public Animal {
public:
    void speak() override {
        std::cout << "Dog" << std::endl;
    }
};

int main() {
    Animal* animal = new Dog();

    animal->speak();

    delete animal;
}

Output:

Dog

If the parent class's speak() is not declared virtual, the above virtual function dynamic dispatch will not occur when calling through Animal*.

4.5 Virtual Function Table (VTable)

In many C++ compiler implementations, virtual function dynamic dispatch is usually implemented with the help of a virtual function table (Virtual Table, VTable).

It should be emphasized: the C++ standard specifies the language behavior of virtual functions and does not mandate that compilers use a VTable. VTable is a mainstream implementation technique.

Its conceptual structure can be understood as:

Animal type
    speak() -> Animal::speak

Dog type
    speak() -> Dog::speak

Cat type
    speak() -> Cat::speak

For objects with virtual functions, a typical implementation stores a pointer to the virtual function table in the object, often called vptr.

The virtual function call process can be abstracted as: