What is Polymorphism?
Polymorphism is a fundamental concept in object-oriented programming that allows objects of different types to be treated as objects of a common superclass. The word "polymorphism" means "many forms," and in Java, it refers to the ability of a single interface to represent different underlying forms (data types or classes).
Key Points:
- Polymorphism allows you to write more flexible and reusable code
- It enables you to perform a single action in different ways
- In Java, polymorphism is often achieved through method overriding and interfaces
- It's closely related to inheritance and interfaces
Here's a simple example to illustrate the concept of polymorphism:
class Animal {
public void makeSound() {
System.out.println("The animal makes a sound");
}
}
class Dog extends Animal {
@Override
public void makeSound() {
System.out.println("The dog barks");
}
}
class Cat extends Animal {
@Override
public void makeSound() {
System.out.println("The cat meows");
}
}
public class PolymorphismExample {
public static void main(String[] args) {
Animal myAnimal = new Animal();
Animal myDog = new Dog();
Animal myCat = new Cat();
myAnimal.makeSound();
myDog.makeSound();
myCat.makeSound();
}
}
In this example, we have a superclass Animal and two subclasses Dog and Cat. Each subclass overrides the makeSound() method. When we create objects of these classes and call the makeSound() method, the appropriate version of the method is called based on the actual object type, not the reference type. This is polymorphism in action.
Try running this code in the compiler below and observe how polymorphism allows different objects to respond to the same method call in different ways.