Composition vs Inheritance

After performing quite a bit of research on casting, I decided I could post a table, or list of some important things that I found out regarding composition vs. inheritance.

Changing implementation of either technique does not break clients code. Separation of interface and implementation is the key.
Inheritance
  1. Can use polymorphism and dynamic binding
  2. Old code works with new code
  3. Base class is fragile (the interface)
  4. Allows derived class code to reuse base class code
  5. “Is-a” relationship
Composition
  1. Derived = front-end, base = backend, client code still works now.
  2. Can change backend without affecting client.
  3. Can swap objects out at runtime.
  4. Works by delegation, a change is required, but not necessarily to the derived class’s interface which keeps client’s code working.
  5. Use if all you want is code reuse.

Some of this might not make any sense, but I highly recommend reading this link and this link, which explains it all.
This is a simple example provided by the javaworld site that I like. I’m going to copy it here for convenience. Although the example might make more sense if you actually read the article, but the point is that you can change the functionality while keeping the interface the same and without messing up the hierarchy.

The important method to look at is the “peelAnItem(Peelable item)” method. This method can now take any object that inherits from the “Peelable” interface, and each of those objects implement their own peelable wrapper of that “Peelable” interface.

In this case, each derived peel method calls the “base” class’s peel method (fruit) because we want to take advantage of code reuse. But they can also have their own specific functionality as well. Also, if the base “fruit” class/component extends its interface, the “Banana” and “Apple” classes do not have to be recompiled. Now we can extend the fruit interface without having to modify the rest of the hierarchy (banana & apple), unlike inheritance, which would require the user implement an overloaded function for each derived class if the base class was purely abstract with no functionality.

Note that a list of interfaces come from the base class’s methods. By base class I mean the component “fruit.” Because in a normal hierarchy, we can think of a banana and an apple deriving from a fruit class. So if we want to turn a normal hierarchy into a set of components and interfaces, we take the list of base class method names and use them to create a list of interfaces.

Now would be a good time to go back up and re-read the table above that differentiates inheritance vs. composition.


Leave a Reply

You must be logged in to post a comment.