0
0
Javaprogramming~5 mins

Compile-time polymorphism in Java

Choose your learning style9 modes available
Introduction

Compile-time polymorphism lets a program decide which method to use before it runs. It helps make code simpler and easier to use.

When you want to perform similar actions but with different inputs.
When you want to use the same method name for different tasks.
When you want to improve code readability by avoiding many method names.
When you want the program to choose the right method automatically based on input types.
When you want to avoid writing repetitive code for similar operations.
Syntax
Java
class ClassName {
    void methodName() { }
    void methodName(int a) { }
    void methodName(int a, int b) { }
}

Methods have the same name but different parameters (number or type).

The compiler decides which method to call based on the arguments used.

Examples
Two methods named add but with different numbers of inputs.
Java
class Calculator {
    int add(int a, int b) {
        return a + b;
    }
    int add(int a, int b, int c) {
        return a + b + c;
    }
}
Methods named print that accept different types of inputs.
Java
class Printer {
    void print(String s) {
        System.out.println(s);
    }
    void print(int n) {
        System.out.println(n);
    }
}
Sample Program

This program shows three show methods with different parameters. The right one runs based on what we give.

Java
class Demo {
    void show() {
        System.out.println("No parameters");
    }
    void show(int a) {
        System.out.println("One parameter: " + a);
    }
    void show(int a, int b) {
        System.out.println("Two parameters: " + a + ", " + b);
    }

    public static void main(String[] args) {
        Demo obj = new Demo();
        obj.show();
        obj.show(5);
        obj.show(3, 7);
    }
}
OutputSuccess
Important Notes

Compile-time polymorphism is also called method overloading.

The method signature (name + parameters) must be different for overloading.

Return type alone cannot create overloading.

Summary

Compile-time polymorphism means choosing the method to run before the program starts.

It uses the same method name but different parameters.

This makes code easier to read and reuse.