7. Mastering Inheritance and Composition


Additional Information:

Code Reuse

Inheritance and Composition are important because they allow us to reuse code, save time, and build better systems.

Inheritance

Inheritance is great when it comes to Parent-Child Relationships. Althought it does break Encapsulation because data is being passed from one object to another object, it shouldn't be any problem as long as the objects truly have a "IS-A" Relationship. Even if we use inheritance properly, over inheriting can cause a very simple system become complex very quickly.

Composition

Composition relies on "HAS-A" Relationships. Composition does not break our Encapsulation rule and allows us to create complex objects by breaking them down into smaller objects. Composition has the same issue as Inheritance, over composition can cause a very simple system become complex very quickly.

There is also two other concepts which allow us to reuse code. Those two concepts are Aggregation and Association. The author believes that aggregation and association are different types of composition and we will be covering in them in another chapter.

Finding a Balance

It is important to know when to use which. The best way to know which one to use is by the type of relationship the objects have. If the objects have a "Has-A" Relationship then it would be best to use Composition but if the objects have a "Is-A" Relationship then it would be best to use Inheritance. Be sure to be positive that the objects truly have an 'Is-A' relationship if you are going to use inheritance. Do not over inherit or over composite your system. Be sure to know what your system will need and what it will not need. There is no need to create unnecessary classes.

Conclusion

Inheritance = IS-A Relationship
Composition = HAS-A Relationship


Download Lesson Notes

The Object-Oriented Thought Process

Author: Matt Weisfeld