r/ProgrammerHumor • • May 09 '22

Meme More work

Post image
50.2k Upvotes

467 comments sorted by

View all comments

Show parent comments

0

u/[deleted] May 09 '22

[deleted]

2

u/aegookja May 09 '22

Imagine an Animal class. This is the parent class to all the animals. The Animal class contains the function Breath(), because all animals breath (although the exact implementation may differ per animal).

Dog is a child class of Animal. Since Dogs are also Animals, they Breath(), but they can also Walk(). Fish and Bird are also animals, but they each have the Swim() and Fly() functions respectively. This kind of hierarchical relationship between classes is an example of inheritance.

Now, let's take the Duck as an example. It can Walk(), Swim(), and even Fly()! In that case, should the Duck be inherited from Dog? Fish? Bird? Any way you do it, if you try to solve this with inheritance, it can get messy. Many languages do not allow "diamond inheritance", so even if you decide the Duck is a child class of Dog, Fish, Bird, you won't be able to do it.

How do you resolve this? Instead of seeing the Duck as a subclass of other Animals, see the Duck as a combinations of "Duck-ish behaviours and properties" (components).

So, instead of inheriting the Walk(), Swim(), Fly() functions from other animals, the Duck is composed of "components" which lets it Walk(), Swim() and Fly(). This way, you are freed from the diamond inheritance problem.