Polymorphism
Polymorphism means one method or object behaving differently in different situations.
It helps in:
Writing flexible code
Managing large applications easily
In simple terms:
One form, many behaviors
Types of Polymorphism
Compile-Time Polymorphism (Static Polymorphism)
Runtime Polymorphism (Dynamic Polymorphism)
1. Compile-Time Polymorphism
Achieved using Method Overloading
Method Overloading
Method overloading means:
Same method name
Different parameters
Rules:
Method name must be same
Parameters must be different
Return type can be same or different
class Soft {
public static void main(String[] args) {
A obj = new A();
obj.m1();
obj.m1(10);
obj.m1(10, "Soft");
}
}
class A {
void m1() {
System.out.println("m1()");
}
void m1(int a) {
System.out.println("m1(int)");
}
void m1(int a, String s) {
System.out.println("m1(int, String)");
}
}Execution depends on method parameters at compile time
2. Runtime Polymorphism
Achieved using:
Dynamic Method Dispatch
Method Overriding
Dynamic Method Dispatch
It means:
A parent class reference can hold child class object
class A {}
class B extends A {}
class Soft {
public static void main(String[] args) {
A obj = new B(); // valid
}
}Important Cases
A obj = new B();→ ValidB obj = new A();→ Compile-time errorCasting wrong object → Runtime error
Method Overriding
Method overriding means:
A child class provides a new implementation of a parent class method
Rules:
Method name must be same
Parameters must be same
Return type must be same
Access modifier can be same or more open
class A {
void show() {
System.out.println("A class method");
}
}
class B extends A {
void show() {
System.out.println("B class method");
}
}
class Soft {
public static void main(String[] args) {
A obj = new B();
obj.show(); // calls B method
}
}Key Point:
Method call is decided at runtime
class University {
void generateId() {}
}
class Student extends University {
void generateId() {
System.out.println("Student ID starts with S");
}
}
class Teacher extends University {
void generateId() {
System.out.println("Teacher ID starts with T");
}
}
class Admin extends University {
void generateId() {
System.out.println("Admin ID starts with A");
}
}
class Soft {
public static void main(String[] args) {
University u;
u = new Student();
u.generateId();
u = new Teacher();
u.generateId();
u = new Admin();
u.generateId();
}
}Why this is important?
Same method
generateId()Different outputs
Clean and scalable code