0
0
JavaConceptBeginner · 3 min read

Compile Time Polymorphism in Java: Definition and Example

In Java, compile time polymorphism means the ability of a class to have multiple methods with the same name but different parameters, decided during compilation. This is also called method overloading, where the compiler chooses the correct method to run based on the method signature.
⚙️

How It Works

Compile time polymorphism in Java happens when the compiler decides which method to call before the program runs. Imagine you have a toolbox with several screwdrivers of different sizes. When you pick one, you choose the right size for the screw. Similarly, the compiler picks the right method based on the number or type of inputs you give.

This is different from runtime polymorphism, where the decision happens while the program is running. Here, the choice is fixed early, making the program faster and easier to understand. The key is that methods share the same name but differ in their parameters, so the compiler knows exactly which one to use.

💻

Example

This example shows a class with two methods named add. One adds two numbers, and the other adds three numbers. The compiler picks the right method based on how many numbers you give.

java
public class Calculator {
    // Method to add two integers
    public int add(int a, int b) {
        return a + b;
    }

    // Overloaded method to add three integers
    public int add(int a, int b, int c) {
        return a + b + c;
    }

    public static void main(String[] args) {
        Calculator calc = new Calculator();
        System.out.println(calc.add(5, 10));       // Calls add(int, int)
        System.out.println(calc.add(5, 10, 15));   // Calls add(int, int, int)
    }
}
Output
15 30
🎯

When to Use

Use compile time polymorphism when you want to perform similar actions but with different inputs. For example, a calculator might add numbers, but sometimes you add two numbers, other times three or more. Instead of creating different method names, you use the same name with different parameters.

This makes your code cleaner and easier to read. It is useful in situations like formatting data, logging messages with different details, or processing inputs of various types without confusing method names.

Key Points

  • Compile time polymorphism is also called method overloading.
  • The method to call is decided by the compiler based on method signatures.
  • It improves code readability by using the same method name for similar actions.
  • It happens before the program runs, so it is fast and efficient.

Key Takeaways

Compile time polymorphism in Java is method overloading where the compiler chooses the method based on parameters.
It helps write cleaner code by using the same method name for different input types or counts.
The decision happens during compilation, making the program faster.
Use it when similar operations need to handle different kinds or numbers of inputs.