7. Polymorphism in Java
One method or object performing different tasks: Method Overloading & Method Overriding.
What is Polymorphism?
English Definition
Polymorphism means "one thing having many forms". In Java, it allows one method or object to perform different tasks.
Hinglish Explanation
Polymorphism ka matlab hai ek cheez ke anek roop! Java mein ek hi method alag-alag situation mein alag-alag kaam kar sakta hai.
1. Compile-Time Polymorphism
Achieved via Method Overloading (resolved at compile time based on parameters).
2. Runtime Polymorphism
Achieved via Method Overriding (resolved at runtime based on the actual object).
Compile-Time Polymorphism: Method Overloading
Method Overloading means creating multiple methods with the same name but different parameters (different count or data types) in the same class.
Main.java — Calculator Return-Value Overloading
class Calculator {
int add(int a, int b) {
return a + b;
}
int add(int a, int b, int c) {
return a + b + c;
}
}
class Main {
public static void main(String args[]) {
Calculator c = new Calculator();
System.out.println(c.add(10, 20));
System.out.println(c.add(10, 20, 30));
}
}
Console Output30
60
Main.java — Calculator Overloading (Different Types & Parameters)
class Calculator {
void add(int a, int b) {
System.out.println(a + b);
}
void add(int a, int b, int c) {
System.out.println(a + b + c);
}
void add(double a, double b) {
System.out.println(a + b);
}
}
class Main {
public static void main(String args[]) {
Calculator c = new Calculator();
c.add(10, 20);
c.add(10, 20, 30);
c.add(10.5, 20.5);
}
}
Console Output30
60
31.0
Runtime Polymorphism: Method Overriding
Method Overriding means using the same method name and same parameters in both parent and child classes, but with a different method body.
Main.java — Parent & Child Overriding
class Parent {
void show() {
System.out.println("Parent class");
}
}
class Child extends Parent {
void show() {
System.out.println("Child class");
}
}
class Main {
public static void main(String args[]) {
Child obj = new Child();
obj.show();
}
}
Console OutputChild class
Method Overloading vs Method Overriding
| Aspect | Method Overloading | Method Overriding |
|---|---|---|
| Polymorphism Type | Compile-Time Polymorphism | Runtime Polymorphism |
| Where Defined | Inside the same class | Across Parent and Child classes (Inheritance) |
| Parameters | Must be different (number or type) | Must be identical |
| Method Body | Can differ per overload | Child provides its own implementation body |