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.
![](https://cdn.codegym.cc/images/article/6cea91f8-acd3-46f7-b3e0-5f70ab825b9c/original.jpeg)
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.
![Polymorphism in Java](https://cdn.codegym.cc/images/article/5c0cc5b5-bd4f-474c-8acd-a9258e1802f9/1024.jpeg)
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?
![Polymorphism in Java. Inheritance](https://cdn.codegym.cc/images/article/ec849d92-b871-4f15-9f23-2c02c3681898/1024.jpeg)
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.
![Method overriding](https://cdn.codegym.cc/images/article/c635e4bd-ab07-4e14-ad6b-738e1406cecc/1024.jpeg)
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