| Consider how these things get stored. In the inheritance model, you might have a big quad tree or some other data structure of PhysicsObjects, and just run through and call updatePhysics() on all of them. In the composition model, we now have multiple classes (Character, Pickup, Projectile), each with an unrelated updatePhysics(). This means code duplication to call the relevant method on each separate class. We could relate them all via an interface, instead of inheritance; now we can store IEntity or whatever. We will soon discover three needs that are awkward to address: 1. Whenever we want to add some new method (say `fall`), we must go back and implement it separately in each class. 2. Different classes will want to share implementations. For example, both Characters and Pickups bounce on fall. 3. Some classes will want to specialize an implementation to do more. Characters bounce on fall, but also take damage. In practice you may end up with both: an interface that your engine talks to, but also a common base class that provides sane defaults. So while interfaces allow uniform interactions with disparate classes, inheritance provides that and also the ability to share and specialize the implementations. So inheritance solves some problems that interfaces cannot. See also default methods in Java, which makes an interface more like a class, and implementing an interface more like inheritance. The documentation even says that a class that implements an interface inherits its default methods. |