Combination of Java Notes is greater than Inheritance

Inheritance is a polymorphism tool, not a code reuse tool. Some developers prefer to use inheritance to achieve code reuse, even in the absence of polymorphism. The rule for whether to use inheritance is that inheritance can only be used when there is a "parent-child" relationship between classes.

Don't inherit just for code reuse. When you use composition to achieve code reuse, there is no inheritance relationship. Overuse of inheritance (via the "extends" keyword) can break all subclasses if the parent class is modified. This is because the tightly coupled relationship between subclasses and superclasses is generated at compile time.

Don't inherit just for the sake of polymorphism. If there is no inheritance relationship between your classes, and you want to achieve polymorphism, then you can achieve it through interfaces and composition, which not only achieves code reuse, but also achieves runtime flexibility.

This is why the Gang of Four design pattern favors composition over inheritance. The interviewer will focus on these words in your answer - "coupling", "static or dynamic", and "happened at compile time or runtime". Runtime flexibility can be achieved through composition, because classes can be dynamically composed at runtime, conditionally or unconditionally, based on a result. But inheritance is static.

Both composition and inheritance can achieve class extension.

The differences are shown in the table below:

write picture description here

The specific implementation of composition is: instead of extending the existing class, a private field is added to the new class, which refers to an instance of the existing class. This way the existing class becomes a component of the new class, each instance method in the new class can call the corresponding method in the contained existing class instance and return its result, this is called forwarding, the new class The methods in are called forwarding methods.

Because each instance of a new class wraps an instance of an existing class, it is also called a wrapper class, and this design pattern is called the decorator pattern. Except that the wrapper class is not suitable for use in the callback framework (callback framework), there are almost no disadvantages. Since the implementation details are not exposed, the obtained API will not limit you to the original implementation, thus ensuring the performance of the class and avoiding the generation of the client. Semantic confusion.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325768230&siteId=291194637