Polymorphism is a programming language feature that allows values of different data types to be handled using a uniform interface.
Let we have superclass Animal and these subclasses: Dog, Cat, Wolf, Hippo and Lion.
First of all, with polymorphism, the reference and the object can be different: Animal myCat= new Cat();. The reference variable type is declared as Animal, but the object is created as new Cat().
With polymorphism, the reference type can be a superclass of the actual object type. This lets to do things like make polymorphic arrays.
We can have polymorphic arguments and return types.
So with polymorphism, we can write code that doesn't have to change when we introduce new subclass types into the program.
class Animal {
public void makeSound() {
System.out.println("The animal makes a sound");
}
}
class Dog extends Animal {
public void makeSound() {
System.out.println("The dog barks");
}
}
class Cat extends Animal {
public void makeSound() {
System.out.println("The cat meows");
}
}
public class Main {
public static void main(String[] args) {
Animal myCat = new Cat();
myCat.makeSound(); // Outputs: The cat meows
}
}