Most design patten books say we should “Favor object composition over class inheritance.”
But can anyone give me an example that inheritance is better than object composition.
Advertisement
Answer
In Java, whenever you inherit from a class, your new class also automatically becomes a subtype of the original class type. Since it is a subtype, it needs to adhere to the Liskov substitution principle.
This principle basically says that you must be able to use the subtype anywhere where the supertype is expected. This severely limits how the behavior of your new inherited class can differ from the original class.
No compiler will be able to make you adhere to this principle though, but you can get in trouble if you don’t, especially when other programmers are using your classes.
In languages that allow subclassing without subtyping (like the CZ language), the rule “Favor object composition over inheritance” is not as important as in languages like Java or C#.