← Java OOP Knowledge Map← Java OOP 知识地图
Object-Oriented Design

Object-Oriented Design面向对象设计

This page maps OOP names to code shapes: inheritance, composition, forwarding, overriding, overloading, interfaces, and polymorphism.这页用代码把 OOP 术语对上:什么时候叫 inheritance,什么时候叫 composition,什么时候叫 forwarding、overriding、overloading。

Procedural vs OOP

Procedure-oriented vs object-oriented函数导向 vs 对象导向

// procedural style
double a = area(circle);
move(circle, 10, 20);

// OOP style
double a = circle.area();
circle.move(10, 20);

Procedural code focuses on actions/functions. OOP focuses on objects that carry data and behaviour together.Procedural 更强调“步骤/函数”;OOP 更强调“对象自己带着数据和行为”。

Inheritance / is-a

Inheritance means “is a kind of”继承表达“它是一种谁”

class Student {
    void enrol() {}
}

class UndergraduateStudent extends Student {
    void chooseMajor() {}
}

UndergraduateStudent extends Student should mean an undergraduate student is a student, not merely “I want to reuse code”.UndergraduateStudent extends Student 的意思不是单纯“我想复用代码”,而是本科生是一种学生。

First ask: does “A is a B” sound true? If not, inheritance is probably wrong.判断继承先问一句:A is a B 说得通吗?如果说不通,大概率不要继承。
Composition / has-a

Composition means “has one inside”组合表达“它里面有谁”

class GraphicalCircle {
    private Circle circle;

    double area() {
        return circle.area();
    }
}

GraphicalCircle has a Circle. Calling circle.area() from area() is method forwarding.GraphicalCircle 里面有一个 Circlearea() 转头调用 circle.area(),这个动作叫 method forwarding。

Abstract Class / Interface

Abstract classes and interfaces define required behaviour抽象类和接口规定必须会什么

abstract class Shape {
    abstract double area();
}

interface Drawable {
    void draw(Graphics g);
}

Shape says every shape must have area(). Drawable says anything implementing it must have draw().Shape 规定所有 shape 必须有 area()Drawable 表示实现它的类必须会 draw()

Overriding / Overloading / Polymorphism

Three names that are easy to mix up三个很容易混的词

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

void print(String text) {}
void print(int number) {}

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