1.代码重用的意义
Code reuse is one of the greatest advantages that object-oriented programming languages provide. Once a class has been created and tested, it should (ideally) represent a useful unit of code.
代码重用是面向对象编程所能提供的一大优势。一般而言,当我们设计好一个类后,我们可以把它作为一个有用的代码模块。
2.重用选择–组合Composition
Code reuse is one of the greatest advantages that object-oriented programming languages provide. Once a class has been created and tested, it should (ideally) represent a useful unit of code.
The simplest way to reuse a class is to just use an object of that class directly, but you can also place an object of that class inside a new class. We call this “creating a member object.”
Because you are composing a new class from existing classes, this concept is called composition (if the composition happens dynamically, it’s usually called aggregation). Composition is often referred to as a “has-a” relationship, as in “A car has an engine”.
当然最简单重用一个对象的类就是直接使用这个类的一个对象,但是我们可以将某个类的对象实例放在一个新的类中,这种方式叫做“创建一个成员对象”。
重用一般是指代一种”has-a”关系,比如“A car has an engine”.
3.重用选择–继承inheritance
We often refer to the relationship between the base class and derived class in this case as an is-a relationship, because you can say, “A circle is a shape.”
A test for inheritance is to determine whether you can state the is-a relationship about the classes and have it make sense.
首先,继承一般是一种”Is-a”关系,比如可以说”A circle is a shape”.
You have two ways to differentiate your new derived class from the original base class.
The first is quite straightforward: you simply add brand new methods to the derived class.
The second and more important way to differentiate your new class is to change the behavior of an existing base-class method. This is referred to as overriding that method.
可以通过2种主要的方式表现出继承关系来:
其一是,通过在子类中增加新的方法;
其二是,改变父类中已存在的基类方法,这就是所谓的重写overriding.