What is Method Overloading in Java: Simple Explanation and Example
method overloading means creating multiple methods in the same class with the same name but different parameters (type, number, or order). It allows a method to perform similar tasks with different inputs, making code easier to read and use.How It Works
Method overloading works by defining several methods with the same name but different parameter lists inside one class. When you call the method, Java looks at the number and types of arguments you provide and chooses the matching method to run.
Think of it like ordering coffee: you can ask for a coffee by size, type, or with extra sugar. The coffee shop understands your request based on what details you give. Similarly, Java picks the right method based on the details (parameters) you provide.
Example
This example shows a class with three add methods that add numbers in different ways depending on the input.
public class Calculator { public int add(int a, int b) { return a + b; } public double add(double a, double b) { return a + b; } 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 first method System.out.println(calc.add(5.5, 3.2)); // Calls second method System.out.println(calc.add(1, 2, 3)); // Calls third method } }
When to Use
Use method overloading when you want to perform similar actions but with different types or numbers of inputs. It helps keep your code clean and easy to understand by using the same method name for related tasks.
For example, in a calculator app, you might want to add two numbers, three numbers, or even decimals. Overloading the add method lets you handle all these cases without confusing method names.
Key Points
- Method overloading happens within the same class.
- Methods must differ in parameter type, number, or order.
- Return type alone cannot distinguish overloaded methods.
- It improves code readability and usability.