Polymorphism is a fundamental concept in Object-Oriented Programming. It refers to the ability of objects to take on different forms or behaviors depending on the context in which they are used. In other words, polymorphism allows different objects to be treated as if they were the same type of object.
There are two types of polymorphism:
1. Compile-time polymorphism (or method overloading): It allows multiple methods with the same name but different parameters to exist within the same class. The correct method is determined at compile-time based on the method signature.
2. Runtime polymorphism (or method overriding): It allows different implementations of a method to be called based on the type of object that is calling the method. The correct method is determined at runtime based on the object’s actual type.
Here is an example of runtime polymorphism in Java:
class Animal{
public void makeSound(){
System.out.println("Animal sound");
}
}
class Dog extends Animal{
public void makeSound(){
System.out.println("Bark");
}
}
class Cat extends Animal{
public void makeSound(){
System.out.println("Meow");
}
}
public class Main{
public static void main(String args[]){
Animal myAnimal = new Animal();
Animal myDog = new Dog();
Animal myCat = new Cat();
myAnimal.makeSound(); //output: Animal sound
myDog.makeSound(); //output: Bark
myCat.makeSound(); //output: Meow
}
}
In this example, we have an Animal class and two subclasses: Dog and Cat. Each subclass overrides the makeSound() method of the Animal class with its own implementation. In the Main class, we create objects of the Animal, Dog and Cat classes and call the makeSound() method on each object. The output shows that each object’s makeSound() method behaves differently based on the object’s actual type. This is an example of runtime polymorphism.