"Hello, Amigo! We've finally come to something truly interesting. Today I'm going to tell you about multiple inheritance. Multiple inheritance is indeed a very fascinating and powerful tool. And if it weren't for several problems, then Java would support multiple inheritance of classes. But it doesn't, so we must be content with multiple inheritance of interfaces. Which is also pretty awesome."
Imagine you're writing a computer game. And its characters (your objects) must behave in very complex ways: walk about a map, collect items, perform quests, communicate with other characters, kill someone, save someone else. Let's say you've been able to divide up all the objects into 20 categories. This means that, if you're lucky, you'll be able to get by with only 20 classes to define your objects. But here's the catch: how many unique forms of interaction will these objects have? Each type of object can have unique interactions with 20 other types of objects (we're also counting interactions with objects of the same type). In other words, you'll need to write code for 20 x 20 = 400 interactions! And if the number of unique object types is not 20, but 100, then the number of interactions could be 10,000!
"Whoa! Now I understand why programming is such difficult work."
"It's simple. Thanks to lots of abstractions. And with no small thanks to multiple inheritance of interfaces."
We can often simplify object interaction if roles and/or abilities interact rather than the objects themselves. And as we already know, abilities can easily be added to a class when it implements some interface.
When writing a large program, developers usually do this from the very start:
1) Identify all abilities/roles.
2) Define the interaction between these roles.
3) Then simply assign roles to all the classes.
"Maybe an example?"
"Of course. Let's look at roles in the cartoon «Tom and Jerry»."
Java code | Description |
---|---|
|
— Role/ability to move. |
|
— Role/ability to be eaten. |
|
— Role/ability to eat someone. |
|
Tom is a cat that has three roles: 1) He can move 2) He can eat someone 3) He can be eaten by someone (a dog) |
|
Jerry is a mouse who has two roles: 1) He can move 2) He can be eaten by someone |
|
Killer is a dog with two roles: 1) He can move 2) He can eat someone |
Knowing only these three roles (interfaces), you can write a program and describe the correct interaction between these roles. For example, an object will chase (via the Moveable interface) after the «one you can eat» and run away from the «one who can eat you». And all this without knowing about specific objects. If you add more objects (classes) to the program and keep these roles, it will still work beautifully, controlling the behavior of your objects.
GO TO FULL VERSION