“Value by inheritance” is an old saying that holds true today. Composition and inheritance are designed to increase reuse and reduce duplicate code. Inheritance also has other advantages.
Composition means that if you have a general method that belongs to 2 or more class hierarchies, separate it as a new class and let the class hierarchies have this new class as part of the composition. At the same time, you still do not touch the class hierarchy, you get the advantage of reusable code.
class Aves { ... } class Hawk: Aves { ... } class Mammal { ... } class Bat: Mammal { ... }
In the above example, all Aves (birds) Fly (), (flightless birds such as Penguin or Dodo can still implement fly () without flying). But the bat, which is a mammal, can also fly ()
Now you can pull Fly () as a separate class and approve composition over inheritance (including Fly () as part of Aves)
class FlyBehavior { public void Fly() { ... } }
FlyBehavior can be a class hierarchy with ShortFlightBehavior and LongFlightBehavior, for example.
I hope I have not embarrassed you yet :)
Sandeep GB
source share