Loading content...
Loading content...
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
Compile-Time Polymorphism (Static Polymorphism)
Runtime Polymorphism (Dynamic Polymorphism)
Achieved using Method Overloading
Method overloading means:
Same method name
Different parameters
Method name must be same
Parameters must be different
Return type can be same or different
java
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
Achieved using:
Dynamic Method Dispatch
Method Overriding
It means:
A parent class reference can hold child class object
java
class A {}
class B extends A {}
class Soft {
public static void main(String[] args) {
A obj = new B(); // valid
}
}A obj = new B(); → Valid
B obj = new A(); → Compile-time error
Casting wrong object → Runtime error
Method overriding means:
A child class provides a new implementation of a parent class method
Method name must be same
Parameters must be same
Return type must be same
Access modifier can be same or more open
java
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
}
}Method call is decided at runtime
java
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();
}
}Same method generateId()
Different outputs
Clean and scalable code