Compile-Time Polymorphism

Method overloading

4 min read

Compile-Time Polymorphism

Achieved using method overloading. Method selection happens at compile time.

Code Examples

Same method name, different parameters

java
1
2class Calculator {
3    int add(int a, int b) {
4        return a + b;
5    }
6
7    int add(int a, int b, int c) {
8        return a + b + c;
9    }
10
11    double add(double a, double b) {
12        return a + b;
13    }
14}
15          

Use Cases

  • API convenience
  • Readable code
  • Utility classes

Common Mistakes to Avoid

  • Changing return type only
  • Confusing with overriding