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.

Polymorphism in Java

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

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

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
class Cow
{
   public void printColor ()
   {
      System.out.println("I'm a white whale");
   }

   public void printName()
   {
      System.out.println("I'm a cow");
   }
}

class Whale extends Cow
{
   public void printName()
   {
      System.out.println("I'm a whale");
   }
}
  • Two classes are defined here — Cow and Whale
  • Whale inherits Cow
  • The Whale class overrides the printName() method
public static void main(String[] args)
{
   Cow cow = new Cow();
   cow.printName();
}
This code displays the following text on the screen:
I'm a cow
public static void main(String[] args)
{
   Whale whale = new Whale();
   whale.printName();
}
This code displays the following on the screen:
I'm a whale

After inheriting the Cow class and overriding the printName method, the Whale class actually contains the following data and methods:

class Whale
{
   public void printColor()
   {
      System.out.println("I'm a white whale");
   }

   public void printName()
   {
      System.out.println("I'm a whale");
   }
}
We don't know about any old method.