JavaRush /Java Blog /Random EN /Practice of using polymorphism

Practice of using polymorphism

Published in the Random EN group
Hello! Today we are finishing a series of lectures on the principles of OOP . In this lesson we will talk about polymorphism. Practice of using polymorphism - 1Polymorphism is the ability to treat multiple types as if they were the same type. In this case, the behavior of objects will be different depending on what type they belong to. Let's look at this statement in more detail. Let's start with the first part: "the ability to work with multiple types as if they were the same type." How can different types be one and the same? Sounds a little strange :/ It's actually simple. For example, this situation arises with the normal use of inheritance. Let's see how it works. Let's say we have a simple parent class Catwith a single method run()- “run”:
public class Cat {

   public void run() {
       System.out.println("Бег!");
   }
}
Now let’s create three classes that inherit from Cat: Lion, Tigerand Cheetah, denoting lion, tiger and cheetah.
public class Lion extends Cat {

   @Override
   public void run() {
       System.out.println("Лев бежит со speedю 80 км/ч");
   }
}

public class Tiger extends Cat {

   @Override
   public void run() {
       System.out.println("Тигр бежит со speedю 60 км/ч");
   }
}

public class Cheetah extends Cat {

   @Override
   public void run() {
       System.out.println("Гепард бежит со speedю до 120 км/ч");
   }
}
So we have 3 classes. Let's simulate a situation where we can work with them as if they were the same class. Let's imagine that one of our cats is sick and needs the help of Dr. Aibolit. Let's try to create a class Aibolitthat will be able to treat lions, tigers, and cheetahs.
public class Aibolit {

   public void healLion(Lion lion) {

       System.out.println("Лев здоров!");
   }

   public void healTiger(Tiger tiger) {

       System.out.println("Тигр здоров!");
   }

   public void healCheetah(Cheetah cheetah) {

       System.out.println("Гепард здоров!");
   }
}
It would seem that the problem is solved - the class is written and ready to use. But what will we do if we want to expand our program? Now we have only 3 species: lions, tigers, and cheetahs. But there are more than 40 species of cats in the world. Imagine what will happen if we add to the program separate classes for Pallas's cats, jaguars, Maine coons, domestic cats and everyone else. Practice of using polymorphism - 2The program itself, of course, will function, but the class Aibolitwill have to constantly add new methods for treating each type of cat, and as a result it will grow to unprecedented sizes. This is where the property of polymorphism comes into play - “the ability to work with several types as if they were the same type.” We don't need to create countless methods that will do the same thing - treat the cat. One method will be sufficient for all cases at once:
public class Aibolit {

   public void healCat(Cat cat) {

       System.out.println("Пациент здоров!");
   }
}
healCat()We can pass both objects Lionand Tigerobjects to the method Cheetah- they are all Cat:
public class Main {

   public static void main(String[] args) {

       Aibolit aibolit = new Aibolit();

       Lion simba = new Lion();
       Tiger sherekhan = new Tiger();
       Cheetah chester = new Cheetah();

       aibolit.healCat(simba);
       aibolit.healCat(sherekhan);
       aibolit.healCat(chester);
   }
}
Console output:

Пациент здоров!
Пациент здоров!
Пациент здоров!
This is how our class Айболитcan work with different types as if they were the same type. Now let's deal with the second part: "in this case, the behavior of objects will be different depending on what type they belong to." Everything is simple here too. In nature, all cats run differently. At a minimum, their running speed differs. Among our three pets, the cheetah is the fastest, while the tiger and lion run slower. That is, their behavior is different. Polymorphism not only gives us the ability to use different types as one. At the same time, it allows us not to forget about their differences and preserves the behavior specific to each of them. This can be understood with this example. Let’s say that after a successful recovery, our cats decided to run around a little to celebrate. Let's add this to our class Aibolit:
public class Aibolit {

   public void healCat(Cat cat) {

       System.out.println("Пациент здоров!");
       cat.run();
   }
}
Let's try to run the same code to treat three animals:
public static void main(String[] args) {

   Aibolit aibolit = new Aibolit();

   Lion simba = new Lion();
   Tiger sherekhan = new Tiger();
   Cheetah chester = new Cheetah();

   aibolit.healCat(simba);
   aibolit.healCat(sherekhan);
   aibolit.healCat(chester);
}
And this is what the result will look like:

Пациент здоров!
Лев бежит со speedю 80 км/ч
Пациент здоров!
Тигр бежит со speedю 60 км/ч
Пациент здоров!
Гепард бежит со speedю до 120 км/ч
Here we clearly see that the specific behavior of our objects was preserved, although we passed all three animals into a method, “generalizing” each of them to Cat. Thanks to polymorphism, Java perfectly remembers that these are not just three cats, but a lion, a tiger and a cheetah, which run differently. This is the main advantage of using polymorphism - flexibility . When we need to create some functionality common to many types, lions, tigers and cheetahs simply turn into “cats”. All animals are different, but in some situations - a cat is a cat, no matter what species it belongs to :) Here's video confirmation.
When this “generalization” is not required, and on the contrary we need the behavior of species to be different, each type behaves differently. Thanks to polymorphism, you create a single interface (set of methods) for a wide range of classes. Due to this, the complexity of programs is reduced. Even if we expanded the program to 40 types of cats, we would still have the simplest possible interface - one method run()for all 40 cats.
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION