JavaRush /Java Blog /Random EN /The practice of using polymorphism

The practice of using polymorphism

Published in the Random EN group
Hello! Today we are finishing a series of lectures on OOP principles . In this lesson, we will talk about polymorphism. The practice of using polymorphism - 1Polymorphism is the ability to work with 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 still be the same? Sounds a little strange :/ It's actually quite simple. For example, this situation occurs in 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 a lion, a tiger, and a 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 in which we can work with them as if they were the same class. Imagine that one of our cats is ill and needs Dr. Aibolit's help. 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 go. 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 types of cats in the world. Imagine what will happen if we add separate classes to the program for manuls, jaguars, maine coons, domestic cats and all the rest. The practice of using polymorphism - 2The program itself, of course, will function, but in the classAibolitnew methods will have to be constantly added to treat each type of cat, and in the end 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 it were the same type." We do not need to create countless methods that will do the same thing - treat a cat. It will be enough one method for all cases at once:
public class Aibolit {

   public void healCat(Cat cat) {

       System.out.println("Пациент здоров!");
   }
}
In the method, healCat()we can pass both objects Lion, and Tigerand 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." Here, too, everything is simple. In nature, all cats run differently. At the very least, they have different running speeds. Among our three pets, the cheetah is the fastest, while the tiger and lion run slower. That is, they behave differently. Polymorphism not only gives us the ability to use different types as one. At the same time, it also allows you not to forget about their differences and preserves the behavior specific to each of them. This can be understood with this example. Suppose, after a successful recovery, our cats decided to run 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 execute 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 here's what the result will look like:

Пациент здоров!
Лев бежит со speedю 80 км/ч
Пациент здоров!
Тигр бежит со speedю 60 км/ч
Пациент здоров!
Гепард бежит со speedю до 120 км/ч
Here we clearly see that the specific behavior of our objects is preserved, although we passed all three animals to the method, "generalizing" each of them to Cat. Thanks to polymorphism, Java remembers very well that these are not just some kind of cats, but a lion, a tiger and a cheetah, which run in different ways. This is the main advantage of using polymorphism - flexibility . When we need to create some kind of functionality common to many types, lions, tigers and cheetahs simply turn into “cats”. The practice of using polymorphism - 3All animals are different, but in some situations - a cat is a cat, no matter what species it belongs to :) Here's a video confirmation for you.
When this "generalization" is not required, and on the contrary, we need species to behave differently, each type behaves differently. Thanks to polymorphism, you create a single interface (set of methods) for a wide range of classes. This reduces the complexity of programs. 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