Java Polymorphism
Polymorphism ,The word "poly" meaning many, and "morph" meaning form. that is one entity can act in multiple forms.
So, in Java, one method can have multiple forms, meaning that the same method can behave differently based on the object associated with it.
As we know, we can define the same method either within the same class or in two different classes. same method inside class is over loading and in two different claass is overriding.
So There are 2 types of polymorphism.
- Compile-time Polymorphism (Method Overloading)
- Runtime Polymorphism (Method Overriding)
Compile-time Polymorphism (Static Binding)
Compile-time polymorphism is implemented using method overloading, that is, a method having the same name but different parameters. It is also called static binding or early binding. It is called compile-time polymorphism because during compile time, only the Java compiler decides which method to call.
So here the compiler will try to find the matching method name then checks the matching parameter
Example:
class Calculator {
int add(int a, int b) {
return a + b;
}
int add(int a, int b, int c) {
return a + b + c;
}
double add(double a, double b) {
return a + b;
}
}
public class HelloWorld {
public static void main(String[] args) {
Calculator calc = new Calculator();
calc.add(10, 20); // Calls add(int, int)
calc.add(10, 20, 30); // Calls add(int, int, int)
calc.add(10.5, 20.5); // Calls add(double, double)
}
}Here, the method name add() is the same, but its parameters are different.
The compiler identifies which add() method to call based on the arguments.
Therefore, method overloading is called compile-time polymorphism
Runtime Polymorphism (Dynamic Binding)
Run-time polymorphism is implemented using method overriding, that is when the parent class method is inherited to sub class and it has its own implementation. It is also called a dynamic polymorphsim because JVM decides which method to call during runtime only based on the actual object created. It is also called Dynamic method dispatch or late binding.
Example:
class Employee {
void calculateSalary() {
System.out.println("Employee salary calculated");
}
}
class Manager extends Employee {
@Override
void calculateSalary() {
System.out.println("Manager salary calculated");
}
}
class Developer extends Employee {
@Override
void calculateSalary() {
System.out.println("Developer salary calculated");
}
}
class Main {
public static void main(String[] args) {
Employee emp = new Manager();
emp.calculateSalary();
}
}
//Output: Manager salary calculatedHere:
- variable emp → reference of Employee
- new Manager() → object of Manager
- calculateSalary() → Manager's version is called at runtime
So, the method that gets executed depends on the actual object, not the reference type.
See you in next page....🙂