Polymorphism in Java
What is Polymorphism?
- Polymorphism literally means “many forms”.
- Allows a single interface to interact with different types of objects.
- Each object behaves according to its specific type.
Why Use Polymorphism?
- Improves code reusability.
- Promotes extensibility – easily add new behavior.
- Supports loose coupling – program to interface, not implementation.
- Simplifies maintenance and enhances readability.
Types of Polymorphism
- Compile-Time (Static): via method or operator overloading; resolved by compiler.
- Run-Time (Dynamic): via method overriding; resolved by JVM at runtime.
Compile-Time Polymorphism Example
class Calculator {
int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; }
String add(String a, String b) { return a + b; }
}
Same method name add(), different parameters → compiler selects correct one.
Run-Time Polymorphism Example
class Animal {
void sound() { System.out.println("Some noise"); }
}
class Dog extends Animal {
@Override
void sound() { System.out.println("Woof"); }
}
// Usage
Animal a = new Dog();
a.sound(); // prints "Woof"
Reference type: Animal, Actual object: Dog. JVM decides at runtime.
Key Concepts
| Concept | Description |
|---|---|
| Method Overloading | Same method name, different parameters |
| Method Overriding | Subclass provides its own implementation of superclass method |
| Inheritance | Class acquires properties and behaviors of another |
| Dynamic Method Dispatch | Overridden method call resolved at runtime |
Summary
- Polymorphism = many forms
- Enables flexible, reusable, and maintainable code
- Two types: Compile-Time & Run-Time
Detailed Article
Polymorphism is a core concept of object-oriented programming that allows objects of different types to be treated uniformly based on a common interface. Compile-Time Polymorphism is achieved through method overloading, resolved by the compiler. Run-Time Polymorphism is achieved via method overriding, resolved by the JVM at runtime. Key concepts include inheritance, method overloading, method overriding, and dynamic method dispatch. It makes code flexible, extensible, and easier to maintain.