class inheritance and object composition are the two most commonly used techniques for multiplexing.
One: Inheritance
Inheritance is a relationship of is a, for example student inherits person, then student is a person. The advantage of inheritance is that subclasses can override the parent class's methods to easily implement extensions to the parent class.
The disadvantages of inheritance are as follows:
①: The inner details of the parent class are visible to the child class.
②: A method inherited by a subclass from a parent class is determined at compile time, so the behavior of a method inherited from a parent class cannot be changed during run time.
③: If the method of the parent class is modified (for example, if a parameter is added), the method of the subclass must be modified accordingly. So the subclass and the parent class is a high-coupling, which violates the object-oriented thought.
Two: Combination
The combination is the design of the class to add the object of the class to be combined into the class as its own member variable.
Advantages of the combination:
①: The current object can only invoke its method through the contained object, so the inner details of the contained object are not visible to the current object.
②: The current object is a low-coupling relationship with the contained object, and if you modify the code in the class that contains the object, you do not need to modify the code of the current object class.
③: The object that the current object can bind dynamically at run time. You can assign values to the contained objects by using the Set method.
Disadvantages of combination: ①: It is easy to produce too many objects. ②: To be able to combine multiple objects, the interface must be carefully defined.
Thus, the combination is more flexible and more stable than the inheritance, so it is preferred to use the combination at design time. Consider using inheritance only if the following conditions are met:
- A subclass is a special type, not just a role of the parent class
- An instance of a subclass does not need to become an object of another class
- Subclass extension, instead of overwriting or invalidating the function of the parent class
Understand the advantages and disadvantages of combination and inheritance to understand the root of the object design way of reason.
Advantages and disadvantages of inheritance and composition