I am aware that Java doesn’t support multiple inheritance. But if I have to design a class system for say, Animal kingdom. How to represent animals that are hybrids of two different animals? For ex, a Mule (Donkey or Horse?), a Liger (Lion or Tiger). How to inherit both Lion and Tiger classes to make a Liger class?
Is there a way of doing it without making Tiger and Lion as interfaces? What if they cannot be made interfaces?
I am aware that Java doesn’t support multiple inheritance. But if I have to
Share
Inheritance is not the right tool to use in this case. You see, a liger is not a tiger, and neither it is a lion. It has characteristics of both, but it is neither.
Say you go to a zoo and the cage says “Tiger”. You peek in and see this weird gigantic cat that you certainly do not recognize as a tiger. It’s cool, but not a tiger. You also don’t think it’s a lion. It’s not substitutable for either.
So, it should compose a
Lionand aTigerand delegate its behavior to the right one, or “override” their behaviors completely or partially.UPDATE:
Now, what to do if you really want some kind of multiple inheritance, like if you want to derive a
Ligerfrom both aHybridand aFeline? Take a look at Scala traits for a possibility. To implement it in Java, you’d need an interface and a class for each concept in the design that you want to multiply “inherit”. Take a look here for the idea.