Explain the meaning of polymorphism. How polymorphism is achieved at run time? Explain with an example.


Q.) Explain the meaning of polymorphism. How polymorphism is achieved at run time? Explain with an example.

Subject: object oriented programming

Polymorphism:

  • Polymorphism is the ability of a variable, function, or object to take on multiple forms.
  • In computer programming, this means that a variable can hold objects of different subclasses of a base class, or a function can be called with arguments of different types.

How Polymorphism is Achieved at Run Time:

  • When a polymorphic function is called, the compiler determines the type of the argument at runtime and calls the appropriate function body.
  • This is called dynamic binding or late binding.
  • In languages that support static typing, the compiler can sometimes infer the type of the argument at compile time and call the appropriate function body directly.
  • This is called static binding or early binding.

Example:

class Animal {
    public void makeSound() {
        System.out.println("Animal makes a sound");
    }
}

class Dog extends Animal {
    @Override
    public void makeSound() {
        System.out.println("Dog barks");
    }
}

class Cat extends Animal {
    @Override
    public void makeSound() {
        System.out.println("Cat meows");
    }
}

public class Main {
    public static void main(String[] args) {
        Animal animal = new Animal();
        animal.makeSound(); // prints "Animal makes a sound"

        Dog dog = new Dog();
        dog.makeSound(); // prints "Dog barks"

        Cat cat = new Cat();
        cat.makeSound(); // prints "Cat meows"
    }
}

In this example, the makeSound() method is polymorphic. When we call animal.makeSound(), the compiler determines the type of animal at runtime (which is Dog or Cat) and calls the appropriate method body.