1. Balenele și vacile
Iată un fapt zoologic interesant: o vaca este mult mai aproape de o balenă decât, de exemplu, de un hipopotam. Se dovedește că vacile și balenele sunt rude relativ apropiate.
Uite aici. Să vă spunem despre polimorfism — un alt instrument foarte puternic al OOP . Are patru caracteristici.
2. Moștenirea nu este un panaceu
Imaginează-ți că ai scris o Cow
clasă pentru un joc. Are multe domenii și metode. Obiectele acestei clase pot face diverse lucruri: să meargă, să mănânce și să doarmă. Vacile poartă și un clopoțel care sună când merg. Să presupunem că ați implementat totul în clasă până la cel mai mic detaliu.
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