Composition:
Serializable
and
Cloneable
are more difficult to implement
when inheritance is presentAircraft
which overrides equals
, it takes some care when you extend such a class
(Boeing747
) and add a new significant field (fUpperDeck
),
and simultaneously provide a correct implementation of equals
.
A common exception is the template method design pattern.
There, the safest style is to make all items in the abstract base class final
, except for the single
abstract
method which needs to be implemented by the subclass.
An interesting quote from chapter one of Design Patterns:
"That leads us to our second principle of object-oriented design:
Favor object composition over class inheritance.
...Nevertheless, our experience is that designers overuse inheritance as a reuse technique, and designs are often made more reusable (and simpler) by depending more on object composition. You'll see object composition applied again and again in the design patterns."
(Their first principle, stated earlier in the chapter, is "Program
to an interface, not an implementation".)