Comparison of inheritance and combination

Source: Internet
Author: User

Inheritance is a type of white box reuse. The internal details of the parent class are visible to the Child class.

Object combinations do not know each other's Internal details and become black box multiplexing.

Advantages and disadvantages of inheritance:

1)
Subclass can directly define the operation of the parent class.

2)
The Compilation Time is determined and cannot be changed during runtime.

3)
Subclass needs to know the implementation details of the parent class, which partially destroys encapsulation. Child classes and parent classes are too closely dependent. Some changes to the parent class will inevitably lead to changes in child classes. Similar problems have been encountered during development. This dependency limits flexibility and reusability. For example, this problem often occurs in the service system, resulting in code copying.

Advantages and disadvantages of combination (dynamic definition at runtime by obtaining object reference:

1)
Objects interact with each other through interfaces.

2)
The object can only be accessed through an interface. Do not know the details of the other Party. This will not damage encapsulation.

3)
You can use another object to replace this object at runtime, which improves flexibility.

4)
Object implementation is based on interface writing, so there is little dependency on implementation.

5)
Preference combinations help to keep each class encapsulated and concentrated on a single task to improve overall cohesion. Both classes and classes maintain a small scale,

6)
The Design Based on Object combination has more objects (but fewer classes), and the behavior of the system depends on the relationship between objects instead of being defined within a class.

Ideally, new functions should be implemented by combining the original components, rather than creating new components.

The second principle of object-oriented design is to prioritize object combinations rather than class inheritance.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.