🌀 What is Polymorphism?
✅ Simple Definition:
Polymorphism means “many forms.” It allows one thing (like a method) to
behave differently based on the object or inputs.
📦 Real-Life Example:
🧍 Imagine you say "Drive":
● To a car → it moves on wheels.
● To a boat → it sails on water.
● To a plane → it flies in the air.
The command is the same ("Drive"), but each one acts differently → This is
Polymorphism.
🧠 Two Types of Polymorphism in Java:
Type Description Also Called
1. Same method name, different parameters Method
Compile-time Overloading
2. Runtime Same method name, same parameters, different Method Overriding
behavior
🧾 1. Method Overloading (Compile-time
Polymorphism)
Same method name with different arguments.
java
CopyEdit
class Calculator {
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
int add(int a, int b, int c) {
return a + b + c;
}
}
public class Main {
public static void main(String[] args) {
Calculator calc = new Calculator();
System.out.println(calc.add(10, 20)); // 30
System.out.println(calc.add(10.5, 20.3)); // 30.8
System.out.println(calc.add(1, 2, 3)); // 6
}
}
✅ Same method name → add()
✅ Different parameters → works with int, double, etc.
🧾 2. Method Overriding (Runtime Polymorphism)
Same method is defined in parent and child class with same parameters. But behavior
changes based on the object.
java
CopyEdit
class Animal {
void sound() {
System.out.println("Animal makes sound");
}
}
class Dog extends Animal {
void sound() {
System.out.println("Dog barks");
}
}
public class Main {
public static void main(String[] args) {
Animal a = new Dog(); // reference of parent, object of
child
a.sound(); // Output: Dog barks
}
}
✅ Method sound() exists in both Animal and Dog
✅ Which one runs? Depends on the object type
💬 Interview Questions & Answers
Q1. What is Polymorphism in Java?
A: Polymorphism means the ability of a method or object to take many forms. It allows the
same method to behave differently based on the input or object.
Q2. What is the difference between Overloading and Overriding?
Feature Overloading Overriding
Type Compile-time Polymorphism Runtime Polymorphism
Class Same class Parent-child (inheritance)
Parameters Must be different Must be same
Return Type Can be same or different Must be same
Q3. Can you override a static method?
A: No, static methods are not overridden, they are hidden.
Q4. Why is Polymorphism useful?
A:
● Helps in writing flexible and reusable code
● Supports method reusability
● Makes code easier to extend and maintain