Concrete implementation of multiplexing
① code reuse is one of the greatest advantages offered by object-oriented programming languages.
The simplest way to reuse a class is to use an object of that class directly, or you can place an object of that class in a new class. We call it a: Create a member object.
② Combination
Use an existing class to synthesize a new class called a combination. Dynamically occurring combinations are called aggregations. The combination is considered a "has-a" relationship. Because the composition is more flexible, a combination should be considered first when creating a new class.
③ inheritance
By inheriting to the base of the existing class, copy it and then create a new class by adding and modifying the replica. When the source class (the parent Class) changes, the modified copy (subclass, export class, or inheriting Class) also reflects these changes.
A base class contains all the shared attributes and behaviors of all exported types.
When an existing type is inherited, a new type is created. This new type not only contains all members of the current type (although the private member is hidden and inaccessible), but more importantly it replicates the interface of the base class. In other words, all messages that can be sent to the base class object can also be sent to the exported class object. Because the type of message sent to a class is a known type, all means that the exported class has the same type as the base class.
There are two ways to make a difference between a base class and an exported class: 1. Add a method directly in the export class. 2. The behavior of changing methods of an existing base class (the method that overrides the overriding base class in the exported Class).
④is-a and Is-like-a
The ideal way to handle inheritance: pure substitution (substitution principle), the export class and base class are exactly the same type, with exactly the same interface, you can use an export class object to completely replace a base class object. (IS-A)
However, it is sometimes necessary to add a new interface to the export type, which extends the interface, and the new type can still replace the base class, but the substitution is imperfect because the newly added method cannot be accessed in the base class. (IS-LIKE-A)
It's good to design in an alternative way, but we often have to add new methods to the interface of the exported class.
Introduction to Thinking in Java objects (4)