Software

WHAT IS POLYMORPHISM?

Rate this post

The term is formed as a result of the combination of the Greek words “many” (πολύ) and “form” (μορφή). In biology, it can be called the presence of more than one form at the same time in the same habitat.

Polymorphism in object-oriented programming languages is the definition of different behavior to methods in new classes derived from the same base class.

 

If we need to explain it with an example;

Let the “sound” method in the bird return “chirp chirp”, and in the dog class “woof woof”. When this method is used, it will be different depending on the animal class used.
public class Animal{
    public String sound();
}
public class Bird extends Animal{
    public String sound(){
        return "chirp chirp";
    }
}
public class Dog extends Animal{ 
    public String sound(){
        return "woof woof";
    }
}
If we create a main class and test it;

public class Polimorfizm{
 
    public static void main(String[] args){
        Animal animalBird = new Bird();
        System.out.println(animal1.sound());
        
        Animal animalDog = new Dog(); 
        System.out.println(animal2.sound());
         
    } }

If we examine it closely;

Animal animal = new Bird();
Animal animal = new Dog();

Let’s imagine that we make a definition as “animal animal”. We cannot tell from the left side of the equation whether this animal should be a bird or a dog. The right side of the equation will show us the type of animal.

If our animal coded as animal = new Bird() is bird, and if it is animal = new Dog(), we have specified that our animal is a dog. Now what sound will be produced when we call animal.sound()? It’s just that the animal.sound() function cannot tell us which animal it belongs to.

Long story short calling the same function over different types of classes is what we call polymorphism.

animal1.ses() -> “chirp chirp” ,

If the animal2.ses() method is used, it will return “Woof, woof”.

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button