1. Whales and cows
Here's an interesting zoological fact: a cow is much closer to a whale than, for example, to a hippopotamus. It turns out that cows and whales are relatively close relatives.
Look here. Let's tell you about polymorphism — another very powerful tool of OOP. It has four features.
2. Inheritance is not a panacea
Imagine that you have written a Cow
class for a game. It has many fields and methods. Objects of this class can do various things: walk, eat, and sleep. Cows also wear a bell that rings when they walk. Suppose you have implemented everything in the class to the smallest detail.
And then your client comes and says she wants to release a new game level, in which all the action takes place at sea, and the main character is a whale.
You start designing a Whale
class and realize that it is only slightly different from the Cow
class. The logic of both classes is very similar and you decide to use inheritance.
The Cow
class is ideal for taking on the role of the parent class: it has all the necessary variables and methods. All we need to do is give the whale the ability to swim. But there's a problem: your whale has legs, horns, and a bell. After all, this functionality is implemented inside the Cow
class. What can be done here?
3. Method overriding
Method overriding comes to our rescue. If we inherited a method that doesn't quite do what we want in our new class, we can replace that method with another one.
How is this done? In our descendant class, we declare the same method as the method of the parent class that we want to override. We write our new code in it. And that's it — it's as if the old method in the parent class simply doesn't exist.
This is how it works:
Code | Description |
---|---|
|
|
|
This code displays the following text on the screen:
|
|
This code displays the following on the screen:
|
After inheriting the Cow
class and overriding the printName
method, the Whale
class actually contains the following data and methods:
|
We don't know about any old method. |
GO TO FULL VERSION