Composition vs Inheritance

Composition vs Inheritance

The main difference between inheritance and composition is in the relationship between objects.

Composition means HAS A

Inheritance means IS A

You do composition by having an instance of another class C as a field of your class, instead of extending C. 

Example: Car has a Engine and Car is a Automobile.

In programming this is represented as:

class Engine {} // The Engine class.


class Vehicle {} // Vehicle class which is parent to Car class.


class Car extends Vehicle { // Car is a Vehicle, so Car class extends Vehicle class.
    private Engine engine; // Car has an Engine so, Car class has an instance of Engine class as its member.
}

As a mental model, you can think of inheritance as static vertical reuse and composition as dynamic horizontal reuse.

Inheritance is known as the tightest form of coupling in object-oriented programming. Changing a base class can cause unwanted side effects on its subclasses or even all over the codebase.

Composition is a far looser coupling. Combining with Dependency Injection, it brings more flexibility and also allows us to change runtime behavior.

Composition is easily achieved at runtime while inheritance provides its features at compile time.


When is inheritance preferable to composition?

First we need to recognize that inheritance is just a special form of composition. Derived classes are composed of their base classes.

However, the coupling of derived to base is much tighter than composite to component.

The reason for this tight coupling is that inheritance is intimately tied to implementation whereas a component can be abstracted.

The derived class IS an instance of the base class. The composite is not an instance of the component.

So the answer of when to prefer inheritance is a matter of how much implementation is in the base class.

If there is none, as in the case of an interface, the cost of coupling is low. But inheriting a richly populated base class is very risky.


When you should use Inheritance over Composition?

Try to follow these rules:

1) logical ("is a" relationship)

2) the relationship cannot break

3) not deep (up to 2 levels)

4) additive (child doesn't use parent)

If either rule is broken, you should use composition.


Good object-oriented design is not about liberally extending existing classes. Your first instinct should be to compose instead.


要查看或添加评论,请登录

社区洞察

其他会员也浏览了