Skip to content

Method Overloading

This content is for Java. Switch to the latest version for up-to-date documentation.

Method overloading is a feature in Java that allows a class to have multiple methods with the same name but different parameter lists.

public class Calculator {
// Method with two int parameters
public int add(int a, int b) {
return a + b;
}
// Method with three int parameters
public int add(int a, int b, int c) {
return a + b + c;
}
// Method with two double parameters
public double add(double a, double b) {
return a + b;
}
}

Method overloading is resolved at compile time based on:

  1. Number of parameters
  2. Types of parameters
  3. Order of parameters

The Java compiler selects the most appropriate method to call based on the arguments you provide.

  • Methods must have the same name
  • Methods must have different parameter lists
  • Return type alone is not enough to distinguish overloaded methods
  • Access modifiers don’t affect method overloading
class Example {
void display(int num) {
System.out.println("Integer: " + num);
}
void display(String text) {
System.out.println("String: " + text);
}
void display(int num1, int num2) {
System.out.println("Two integers: " + num1 + " and " + num2);
}
// Different order of parameters
void process(int id, String name) {
System.out.println("Processing ID: " + id + ", Name: " + name);
}
void process(String name, int id) {
System.out.println("Processing Name: " + name + ", ID: " + id);
}
}
class InvalidExample {
// Invalid: Only the return type is different
int getValue() { return 10; }
// double getValue() { return 10.5; } // Won't compile
// Valid: Different parameter list
double getValue(double multiplier) { return 10 * multiplier; }
}

Java may automatically promote a data type when searching for a matching method:

class TypePromotion {
void show(int num) {
System.out.println("int method: " + num);
}
void show(double num) {
System.out.println("double method: " + num);
}
public static void main(String[] args) {
TypePromotion obj = new TypePromotion();
obj.show(5); // Calls int version
obj.show(5.5); // Calls double version
obj.show('A'); // Calls int version (char promoted to int)
}
}

Don’t confuse overloading with overriding:

  • Overloading: Multiple methods with the same name but different parameters in the same class
  • Overriding: Replacing a method from a parent class with a new implementation in a child class
  • Improves code readability and reusability
  • Reduces the need for remembering different method names for similar operations
  • Allows methods to handle different data types and parameter counts
Built with passion by Ngineer Lab