Polymorphism in Java
Site Admin
· 11 Sep 2026
· 10 views
One Name, Many Behaviours
Polymorphism means the same method name can express different behaviour depending on the context. Java has two flavours: compile-time and runtime.
Compile-Time Polymorphism (Overloading)
Methods with the same name but different parameter lists are chosen by the compiler based on the arguments you pass.
class Calculator {
static int area(int side) { return side * side; } // square
static int area(int length, int width) { return length * width; }
static double area(double radius) { return Math.PI * radius * radius; }
}
System.out.println(Calculator.area(5)); // 25
System.out.println(Calculator.area(4, 6)); // 24
System.out.println(Calculator.area(2.0)); // circle areaRuntime Polymorphism (Overriding with Dynamic Dispatch)
When a method is overridden, the JVM decides at runtime which version to run, based on the actual object type, not the declared reference type.
Animal ref = new Dog();
ref.speak(); // prints "Woof" - runtime decides
Animal ref2 = new Cat();
ref2.speak(); // prints "Meow"Here the reference type is Animal, but the JVM calls the overridden speak() of the real object (Dog or Cat). This is the key idea that lets generic code work with all subtypes.
Why It Matters
void introduce(Animal creature) {
creature.speak(); // works for ANY Animal subclass
}
introduce(new Dog());
introduce(new Cat());New subclasses can be added without touching this method - the code stays open for extension.
Key Points
- Overloading is decided at compile time by the argument list.
- Overriding is decided at runtime by the actual object type.
- Polymorphism lets generic code handle many types cleanly.