Inheritance and combination
Object-Oriented programming focuses onCodeReuse, inheritance, and combination are both effective methods for code reuse. The combination is to use the objects of other classes as members, and the inheritance is the member method of the Child class that can use the parent class. Reference a vivid example: Inheritance refers to "my father helped me a lot at home". The combination is "I invited an old man to work in my house ".
Inheritance
In the inheritance structure, the internal details of the parent class are visible to the Child class. Therefore, we can also say that the inherited code reuse is a "white box code reuse ".
Advantages:
- It is easy to use and can be easily implemented using syntax keywords.
- It is easy to modify or extend the implementation of the parent quilt class reuse.
Disadvantages:
- The static compilation phase determines the hierarchy and cannot be changed during the runtime.
- This destroys encapsulation. Due to the reuse of white boxes, the internal details of the parent class are usually visible to the Child class.
- Child classes are closely coupled with parent classes. Child classes depend on the implementation of parent classes, and child classes lack independence. When the implementation of the parent class is changed, the Child class also has to be changed.
Combination
Combination creates new and more complex functions by assembling existing objects. Because the internal details of objects are invisible, we also say that code reuse in this way is "black box code reuse ".
Advantages:
- By getting reference to other objects of the same type, you can dynamically define (object) Combinations during runtime.
- The "black box" is reused, and the internal details of the contained object are invisible to the outside world. Without damaging the encapsulation, the overall class and the local class are loosely coupled and independent from each other.
- The overall class encapsulates Department classes, encapsulates local class interfaces, and provides new interfaces, which provides better scalability.
Disadvantages:
- The overall class cannot automatically obtain the same interface as the Department class, and it requires more code than the inheritance implementation.
- Unfamiliar code is hard to understand.
Select both
The is-a relationship is expressed by inheritance, and the has-a relationship is expressed by combination. Inheritance represents a specialized concept, while combination represents an assembly concept.
Personal Recommendation: The combination is preferred unless upward transformation is used.