Polymorphism in Java is one of the core concepts of Object-Oriented Programming (OOP). It allows us to perform a single action in different ways. Polymorphism means "many forms". In simple terms, it allows one interface to be used for multiple implementations, making our code flexible and reusable.
Types of Polymorphism in Java
In Java, polymorphism is classified into two main types:
- Compile-time Polymorphism (Method Overloading)
- Runtime Polymorphism (Method Overriding)
1. Compile-time Polymorphism (Method Overloading)
Compile-time polymorphism occurs when the method call is resolved at compile time. The most common example of this is Method Overloading.
What is Method Overloading?
If a class has multiple methods with the same name but different parameter lists (different number or type of parameters) it is called Method Overloading.
Example:
class Calculator {
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
}
public class Main {
public static void main(String[] args) {
Calculator calc = new Calculator();
System.out.println(calc.add(5, 10)); // calls int version
System.out.println(calc.add(5.5, 10.2)); // calls double version
}
}
Why use it?
- Increases readability of the program
- Same method name with different argument list is easy to remember
Ways to Achieve Overloading
- By changing the number of arguments
- By changing the data type of arguments
2. Runtime Polymorphism (Method Overriding)
Runtime polymorphism, also known as Dynamic Method Dispatch, is achieved through Method Overriding. In this case, the method call is resolved at runtime, not at compile time.
What is Method Overriding?
If a subclass (child class) provides specific implementation of method that is already defined in its parent class, it is called Method Overriding.
Rules for Overriding:
- The method in the child class must have the same name, return type, and parameters as in the parent class.
- It requires inheritance (using
extends
).
Example:
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
@Override
void sound() {
System.out.println("Dog barks");
}
}
public class Main {
public static void main(String[] args) {
Animal a = new Dog(); // Upcasting
a.sound(); // Output: Dog barks (resolved at runtime)
}
}
Why use it?
- To provide a specific implementation in the child class
- To achieve runtime polymorphism.
Conclusion
- Polymorphism makes Java programs more flexible, extensible, and easier to maintain.
- Use Overloading for compile-time decisions and code clarity.
- Use Overriding for dynamic behavior and runtime flexibility.
Top comments (0)