Understanding Compile-Time Polymorphism in Java

Understanding Compile-Time Polymorphism in Java

# programming# webdev# java# polymorphism
Understanding Compile-Time Polymorphism in JavaKarthick Karthick

Compile-Time Polymorphism in Java Introduction Polymorphism is one of the most important concepts in...

Compile-Time Polymorphism in Java
Introduction
Polymorphism is one of the most important concepts in Java. The word "polymorphism" comes from two Greek words:

Poly = Many
Morph = Forms
It allows a single method or object to behave in different ways.
Compile-Time Polymorphism is a type of polymorphism where the method to be executed is determined by the compiler during compilation.
It is also known as:
Static Polymorphism

Early Binding
Method Overloading
What is Compile-Time Polymorphism?
Compile-Time Polymorphism occurs when multiple methods have the same name but different parameter lists. The compiler decides which method should be called based on the arguments passed.
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;
}
Enter fullscreen mode Exit fullscreen mode

}

public 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.5, 20.5));
    System.out.println(c.add(10, 20, 30));
}
Enter fullscreen mode Exit fullscreen mode

}
Output:
30
31.0
60

Method Overloading Rules:
Number of Parameters Changes
Data Type Changes
Order of Parameters Changes

Advantages of Compile-Time Polymorphism
Code Reusability
Same method name can perform similar tasks.
Readability
Program becomes easier to understand.
Flexibility
Methods can handle different types of input.
Faster Execution
Method calls are resolved during compilation.