Back to series
· 13 min read

Object-Oriented Programming (OOP)


I. What Is Object-Oriented Programming?

Object-Oriented Programming (OOP) is a programming paradigm that organizes programs around objects.

It abstracts entities from real-world problems or business domains into objects, storing state and providing behavior through objects, and completing system functionality through collaboration between objects.

Object-oriented programming focuses on questions such as:

  • What objects exist in the system?
  • What responsibility does each object have?
  • What state should be stored inside each object?
  • What operations does each object expose to the outside?
  • How do different objects collaborate?
  • How can extensibility be achieved through inheritance, composition, and polymorphism?

For example, an e-commerce system can be abstracted into the following objects:

  • User: user.
  • Product: product.
  • Order: order.
  • Payment: payment.
  • Inventory: inventory.

Each object is responsible for managing its own related data and behavior, and multiple objects collaborate through method calls, interfaces, or messages.

1. Core Idea

The core idea of object-oriented programming is:

Organize data and the behavior that operates on that data within objects, and build complete programs through collaboration between objects.

A typical object-oriented system can be abstracted as:

flowchart TD
    A["Business Requirements"] --> B["Identify Domain Entities"]
    B --> C["Abstract Objects and Responsibilities"]
    C --> D["Define Classes and Interfaces"]
    D --> E["Create Object Instances"]
    E --> F["Collaboration Between Objects"]
    F --> G["Complete Business Functionality"]

    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:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style F fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style G fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    linkStyle default stroke:#A3B8AC,stroke-width:1.5px

Object-oriented programming is not simply about putting functions into classes; rather, it manages system complexity through reasonable object boundaries, responsibility division, and collaboration relationships.


II. Classes and Objects: The Foundation of Object Orientation

Classes and objects are the two basic concepts for understanding OOP.

1. Class

A class is the abstract definition of an object, used to describe what attributes and behaviors a category of objects has.

For example, define a user class:

public class User {
    String name;
    int age;

    void login() {
        System.out.println("用户登录");
    }

    void logout() {
        System.out.println("用户退出");
    }
}

Here:

  • User: class name.
  • name, age: attributes, used to describe object state.
  • login(), logout(): methods, used to describe object behavior.

A class defines the structure and operations of objects, but the class itself is not equal to any specific object.

2. Object

An object is a concrete instance of a class.

User user1 = new User();
user1.name = "Alice";
user1.age = 25;

User user2 = new User();
user2.name = "Bob";
user2.age = 30;

Both user1 and user2 are instances of the User class, but they have different states.

An object usually contains two important aspects:

  • State: the data currently stored by the object.
  • Behavior: the operations the object can perform.
Concept Description Example
Class Abstract definition of an object User
Object Concrete instance of a class user1
Attribute Describes object state name, age
Method Describes object behavior login()
Instantiation The process of creating an object new User()

3. The Relationship Between Classes and Objects

A class can be understood as the type definition of an object, and an object as a concrete instance of that type.

flowchart TD
    A["User class"] --> B["object instance user1"]
    A --> C["object instance user2"]
    A --> D["object instance user3"]

    B --> E["name = Alice<br/>age = 25"]
    C --> F["name = Bob<br/>age = 30"]
    D --> G["name = Carol<br/>age = 28"]

    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

Points to note:

  • A class is a definition of a type or structure; this does not mean that all languages use the same memory implementation.
  • An object is a runtime entity, but not all objects are necessarily implemented through traditional heap memory allocation.
  • Some languages support prototype objects, structs, or other object models and do not necessarily use the traditional class mechanism.

III. The Four Fundamental Characteristics of Object-Oriented Programming

Object-oriented programming is usually introduced through four core concepts:

  1. Abstraction.
  2. Encapsulation.
  3. Inheritance.
  4. Polymorphism.

Together, these four concepts form the theoretical foundation of classic OOP, but they are not the only implementation approach that every object-oriented language must adopt.

1. Abstraction

Abstraction is the process of extracting key characteristics from complex things and ignoring details irrelevant to the current problem.

For example, when designing a payment system, business code may only care about:

  • The payment amount.
  • The payment method.
  • The payment result.
  • The payment status.

As for how the underlying layer connects to payment channels, how requests are encrypted, and how network retries are handled, these can be hidden in the concrete implementation.

The goal of abstraction is to establish a clear conceptual model and reduce the cost of understanding the system.

Code example:

interface Payment {
    void pay(double amount);
}

After defining the payment interface, different payment channels can implement the same operational contract:

class Alipay implements Payment {
    public void pay(double amount) {
        System.out.println("支付宝支付:" + amount);
    }
}

class WeChatPay implements Payment {
    public void pay(double amount) {
        System.out.println("微信支付:" + amount);
    }
}

The caller only needs to know the Payment interface and does not need to understand the internal implementation of a specific payment channel.

Value of abstraction:

  • Hide complex implementation details.
  • Establish stable business interfaces.
  • Reduce the caller's dependence on concrete implementations.
  • Support replacement between different implementations.

2. Encapsulation

Encapsulation is the organization of data and the methods that operate on that data together, while restricting direct external access to internal state through access control.

For example:

public class Account {
    private double balance;

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

        balance += amount;
    }

    public double getBalance() {
        return balance;
    }
}

Here:

  • balance is a private field.
  • External code cannot directly modify the account balance.
  • deposit() provides a controlled entry point for modification.
  • getBalance() provides a read entry point.

Encapsulation is not just about setting fields to private; more importantly, it protects the object's invariants.

For example, the account balance must not violate business rules due to arbitrary external assignment.

Value of encapsulation:

  • Control data access.
  • Protect object state.
  • Enforce business constraints.
  • Reduce external code's dependence on internal implementation.

3. Inheritance

Inheritance allows one class to be defined based on another class, thereby reusing or extending existing properties and behavior.

For example:

class Animal {
    void eat() {
        System.out.println("动物进食");
    }
}

class Dog extends Animal {
    void bark() {
        System.out.println("狗叫");
    }
}

Dog inherits from Animal, can use the eat() method provided by the superclass, and at the same time adds its own bark() method.

An inheritance relationship can usually be expressed as:

flowchart TD
    A["Animal superclass"] --> B["Dog subclass"]
    A --> C["Cat subclass"]
    B --> D["Inherits eat()"]
    B --> E["Extends bark()"]
    C --> F["Inherits eat()"]
    C --> G["Extends meow()"]

    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:#E8EDF2,stroke:#B8C3CE,color:#334155
    style E fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style F fill:#E8EDF2,stroke:#B8C3CE,color:#334155
    style G fill:#FFF5DE,stroke:#E8D29A,color:#334155
    linkStyle default stroke:#A3B8AC,stroke-width:1.5px

The main purposes of inheritance:

  • Reuse existing implementations.
  • Express relationships between types.
  • Extend existing behavior.
  • Support runtime polymorphism.

However, inheritance also introduces coupling issues.

A subclass may depend on the superclass's internal implementation, and changes to the superclass may affect all subclasses. Therefore, inheritance should express a sound type relationship, rather than being used merely to reduce duplicate code.

4. Polymorphism

Polymorphism means that the same interface or operation can exhibit different behavior on different objects.

For example:

interface Animal {
    void speak();
}

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

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

Caller:

public class Main {
    public static void main(String[] args) {
        Animal animal1 = new Dog();
        Animal animal2 = new Cat();

        animal1.speak();
        animal2.speak();
    }
}

Although both variables are declared as type Animal, the implementations actually invoked are different.

flowchart TD
    A["Animal interface"] --> B["Dog object"]
    A --> C["Cat object"]
    D["Call speak()"] --> E["Select implementation based on the actual object"]
    B --> E
    C --> E
    E --> F["Dog.speak()"]
    E --> G["Cat.speak()"]

    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:#E5F4EC,stroke:#A3CBB5,color:#334155
    style G fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    linkStyle default stroke:#A3B8AC,stroke-width:1.5px

The core value of polymorphism:

  • Callers depend on abstract interfaces.
  • Different implementations can be extended independently.
  • Reduce conditional checks in business code.
  • Improve system extensibility.

It is important to distinguish: polymorphism does not exist only in inheritance hierarchies. Mechanisms such as interface implementation, function overloading, generics, and duck typing can also embody polymorphic ideas at different levels.


IV. Internal Structure and Runtime Mechanism of Objects

Understanding OOP isn't just about the syntax of classes; you also need to know how objects are represented, created, accessed, and destroyed at runtime.

1. Object State and Behavior

An object is usually described along two dimensions: state and behavior.

State:

The data stored inside the object.

For example:

class User {
    String name;
    int age;
    boolean active;
}

Behavior:

The operations an object can perform.

class User {
    String name;
    int age;

    void login() {
        System.out.println(name + " 登录");
    }

    void updateAge(int age) {
        this.age = age;
    }
}

State describes what an object currently looks like; behavior describes what an object can do.

2. Object References and Object Instances

In Java:

User user = new User();

Here we need to distinguish:

  • User: the declared type of the reference variable.
  • user: a local reference variable.
  • new User(): an expression that creates an object instance.
  • =: assigns the object reference to the variable.

Conceptually, this can be represented as:

flowchart LR
    A["reference variable user"] --> B["User object"]
    B --> C["name"]
    B --> D["age"]
    B --> E["login()"]

    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
    linkStyle default stroke:#A3B8AC,stroke-width:1.5px

The diagram here expresses the logical relationship between a reference and an object; it does not mean that all languages use the same memory layout.

In Java, a reference variable holds an object reference; in C++, an object can be stored directly in an automatic-storage-duration object, or accessed indirectly through a pointer or smart pointer.

3. Object Layout in Memory

In a traditional runtime implementation, an object may contain:

  • Instance fields.
  • Alignment padding.
  • Object header.
  • Type or runtime metadata.
  • Garbage-collection-related information.

Taking a typical Java virtual machine implementation as an example, an object usually contains an object header and instance data; the specific layout depends on factors such as the JVM implementation, compressed pointers, and object alignment.

Note the following:

  • A class's methods generally do not need a copy of the machine code for each instance.
  • Multiple objects can share the same class's method implementations.
  • Instance fields usually belong to their respective objects.
  • Static fields belong to the class or the corresponding runtime type state, and are not stored separately per object.

The object layout of one particular virtual machine must not be treated as a universal specification for all object-oriented languages.

4. Constructors and Object Initialization

A constructor is usually used to establish an object's initial state.

For example:

class User {
    private String name;
    private int age;

    public User(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

Creating an object:

User user = new User("Alice", 25);

The construction process can be abstracted as:

flowchart TD
    A["Request object creation"] --> B["Allocate or prepare object storage"]
    B --> C["Initialize default state"]
    C --> D["Execute construction logic"]
    D --> E{"Initialization successful?"}
    E -->|"Yes"| F["Obtain usable object"]
    E -->|"No"| G["Report initialization failure"]

    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:#E5F4EC,stroke:#A3CBB5,color:#334155
    style G fill:#FBE9E9,stroke:#D9AAAA,color:#334155
    linkStyle default stroke:#A3B8AC,stroke-width:1.5px

This is a simplified conceptual flow. Different languages have different rules for memory preparation, field initialization, base class construction, and handling construction failure.

For example:

  • Java uses constructors to initialize objects.
  • C++ establishes object state through constructors and member initializer lists.
  • Python typically creates an instance through __new__(), then initializes the instance through __init__().
  • Rust constructs values through struct expressions and associated functions; it does not have class constructors in the traditional sense.

5. Object Lifecycle

Object lifecycle describes the process of an object from creation until it is no longer valid.

Different languages use different resource management approaches:

Language Common lifecycle management mechanisms
Java Garbage collection
C# Garbage collection
Python Implementation mechanisms such as reference counting and cycle garbage collection
C++ Automatic storage duration, destructors, RAII, smart pointers
Rust Ownership, borrowing, and lifetime rules
Go Garbage collection

In C++:

class User {
public:
    User() {
        std::cout << "创建对象" << std::endl;
    }

    ~User() {
        std::cout << "销毁对象" << std::endl;
    }
};

int main() {
    User user;
    return 0;
}

Local objects usually have their destructors called automatically when they leave their lifetime scope.

In Java, an object's reachability and garbage collection determine when the object can be reclaimed, but the timing of garbage collection is not guaranteed to coincide with the moment the object goes out of scope.


V. Inheritance Mechanisms and the Type System

Inheritance is an important mechanism in object-oriented languages for organizing type relationships.

1. Superclasses and Subclasses

A superclass defines common attributes and behaviors, and subclasses inherit and extend these capabilities.

class Vehicle {
    String brand;

    void start() {
        System.out.println("车辆启动");
    }
}

class Car extends Vehicle {
    int doors;

    void drive() {
        System.out.println("汽车行驶");
    }
}

Car can use the brand and start() inherited from Vehicle, and can also define its own doors and drive().

2. Method Overriding

A subclass can reimplement a method already defined by its superclass.

class Animal {
    void speak() {
        System.out.println("动物发声");
    }
}

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

Call:

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

If the method participates in dynamic dispatch, the implementation in Dog will be executed.

Method overriding is an important foundation for runtime polymorphism.

3. Single Inheritance and Multiple Inheritance

Different languages provide different support for inheritance hierarchies.

Language Class Inheritance Characteristics
Java Classes use single inheritance; interfaces support multiple implementations
C# Classes use single inheritance; interfaces support multiple implementations
C++ Supports multiple inheritance
Python Supports multiple inheritance
Go Does not provide traditional class inheritance; abstraction is mainly implemented through composition and interfaces
Rust Does not provide traditional class inheritance; abstraction is mainly implemented through composition and traits

Multiple inheritance can express more complex type relationships, but it also brings:

  • The diamond inheritance problem.
  • Complex method resolution order.
  • Duplicated parent class state.
  • Type relationships are difficult to understand.
  • Increased maintenance cost.

C++ handles part of the diamond inheritance problem through mechanisms such as virtual inheritance, while Python determines method lookup order through MRO (Method Resolution Order).

4. Inheritance and Composition

Inheritance expresses a relationship at the type level and is usually suitable for representing an “is-a” relationship.

Composition expresses a containment or collaboration relationship between objects and is usually suitable for representing a “has-a” relationship.

For example:

class Engine {
    void start() {
        System.out.println("发动机启动");
    }
}

class Car {
    private Engine engine = new Engine();

    void start() {
        engine.start();
    }
}

Here, Car has an Engine through composition, rather than inheriting from Engine.

In complex systems, composition is usually more flexible than deep inheritance.


VI. Polymorphism and Dynamic Binding

Polymorphism is a very important mechanism in OOP and is also key to understanding object-oriented runtime behavior.

1. Static Type and Dynamic Type

Take Java as an example:

Animal animal = new Dog();

There are two different concepts here:

  • Static Type: the type at variable declaration, namely Animal.
  • Dynamic Type: the actual type of the object at runtime, namely Dog.

Static type mainly affects compile-time type checking and whether member access is legal.

Dynamic type participates in certain runtime method dispatch.

2. Dynamic Binding

Dynamic binding means that the specific implementation of a method call is determined at runtime based on the object's actual type.

For example:

class Animal {
    void speak() {
        System.out.println("动物发声");
    }
}

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

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

Call:

Animal[] animals = {
    new Dog(),
    new Cat()
};

for (Animal animal : animals) {
    animal.speak();
}

Runtime call process:

flowchart TD
    A["Call animal.speak()"] --> B["Read the actual object type"]
    B --> C{"Actual type"}
    C -->|"Dog"| D["Execute Dog.speak()"]
    C -->|"Cat"| E["Execute Cat.speak()"]
    D --> F["Return to caller"]
    E --> F

    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:#E5F4EC,stroke:#A3CBB5,color:#334155
    style F fill:#E8EDF2,stroke:#B8C3CE,color:#334155
    linkStyle default stroke:#A3B8AC,stroke-width:1.5px

It is necessary to distinguish here:

  • Method overriding is a behavior definition at the language level.
  • Dynamic binding is the mechanism that selects the specific implementation at runtime.
  • The virtual method table (VTable) is a common implementation approach in some compiled languages; it is not the only mechanism that polymorphism must use.

3. Virtual Functions and Virtual Method Tables

In C++, virtual can be used to declare a virtual function.

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

    virtual ~Animal() = default;
};

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

Call:

Animal* animal = new Dog();
animal->speak();

delete animal;

Since speak() is a virtual function, calls are dynamically dispatched based on the object's dynamic type.

In common C++ ABI implementations, compilers usually use a virtual table (VTable) to support dynamic dispatch.

Conceptually, this can be understood as:

  • An object is associated with its corresponding dynamic type information.
  • A type corresponds to a set of virtual function entries.
  • A virtual function call locates the actual implementation based on the dynamic type.

However, note the following:

  • The C++ standard does not mandate the use of a VTable.
  • The specific layout of a VTable is determined by the ABI and compiler implementation.
  • Not all member functions are called through a virtual function table.
  • The compiler may optimize through devirtualization, converting dynamic calls into direct calls.

7. Interfaces and Abstract Classes

Interfaces and abstract classes are both important tools for establishing abstraction boundaries, but their semantics are not the same.

1. Interface

An interface defines a set of behavioral contracts, with concrete implementations provided by the types that implement the interface.

interface Storage {
    void save(String data);
    String read();
}

Different storage mechanisms can implement the same interface:

class FileStorage implements Storage {
    public void save(String data) {
        System.out.println("保存到文件");
    }

    public String read() {
        return "文件数据";
    }
}

class DatabaseStorage implements Storage {
    public void save(String data) {
        System.out.println("保存到数据库");
    }

    public String read() {
        return "数据库数据";
    }
}

The caller only needs to depend on Storage:

void process(Storage storage) {
    storage.save("hello");
}

This frees business logic from having to depend directly on the concrete implementations of file storage or database storage.

2. Abstract Class

An abstract class is a class that cannot be instantiated directly and is usually used to define shared state and partial behavior.

abstract class Animal {
    protected String name;

    public Animal(String name) {
        this.name = name;
    }

    abstract void speak();

    void sleep() {
        System.out.println(name + " 正在睡觉");
    }
}

A subclass must implement the relevant abstract methods according to the language's rules before it can become an instantiable concrete type.

3. Comparison of Interfaces and Abstract Classes

Comparison Dimension Interface Abstract Class
Core Role Define behavioral contracts Provide shared abstraction and partial implementation
Instantiation Usually cannot be instantiated directly Cannot be instantiated directly
State Usually does not carry ordinary instance state storage Can contain instance fields
Method Implementation Depends on the language; may allow default implementations Can contain concrete methods
Inheritance Relationship A type can implement multiple interfaces A Java class can inherit from only one class
Main Use Decouple implementations and unify calling conventions Share state and common implementations

The specific capabilities of interfaces and abstract classes vary by language. For example, Java interfaces support default methods, while C++ usually expresses interface-like concepts through abstract classes containing pure virtual functions.


8. Relationships Between Objects

Object-oriented systems contain not only individual objects but also relationships between objects.

1. Association

An association indicates that some business relationship exists between two objects.

For example: