Polymorphism is one of the core principles of Object-Oriented Programming in Java. It allows a single method or object to behave differently based on the context. The word polymorphism means many forms.
Java supports two types of polymorphism:
// Parent class
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
// Child class overriding method
class Dog extends Animal {
void sound() {
System.out.println("Dog barks");
}
}
// Main class demonstrating polymorphism
public class Main {
public static void main(String[] args) {
Animal a = new Dog();
a.sound();
}
}
Dog barks
Although the reference type is Animal, the overridden method of Dog is called at runtime. This is runtime polymorphism.
Change the object type below to see how the same line of code executes different logic at runtime.
Shape with method draw()draw() in Circle and Rectangle