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。
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 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 的意思不是单纯“我想复用代码”,而是本科生是一种学生。
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 里面有一个 Circle。area() 转头调用 circle.area(),这个动作叫 method forwarding。
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()。
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();
- overriding: a subclass rewrites a superclass method with the same signature.:子类重写父类同名同参数方法。
- overloading: same method name, different parameters.:同名方法,不同参数。
- polymorphism: the variable type may be parent class, but runtime dispatch uses the real object type.:变量类型可以是父类,但运行时根据真实对象类型调用方法。