Method Overloading is a feature in Java where multiple methods can have the same name but different parameters. It allows methods to perform different tasks based on the number or type of parameters passed to them.
In method overloading, you can define multiple methods with the same name in a class, as long as they have different method signatures. The method signature includes the method name and the parameter list (number and type of parameters).
class Calculator {
// Method to add two integers
public int add(int a, int b) {
return a + b;
}
// Method to add three integers (Overloaded method)
public int add(int a, int b, int c) {
return a + b + c;
}
// Method to add two double numbers (Overloaded method)
public double add(double a, double b) {
return a + b;
}
}
In the example above, the add method is overloaded three times with different parameter types and numbers of parameters.
Letβs see how method overloading works in Java. The following example demonstrates how different add methods are called based on the arguments passed.
public class Main {
public static void main(String[] args) {
Calculator calc = new Calculator();
// Calling add method with two integers
System.out.println("Sum of 2 and 3: " + calc.add(2, 3));
// Calling add method with three integers
System.out.println("Sum of 2, 3, and 4: " + calc.add(2, 3, 4));
// Calling add method with two doubles
System.out.println("Sum of 2.5 and 3.5: " + calc.add(2.5, 3.5));
}
}
In this example, we are calling the overloaded add methods with different numbers and types of arguments. The correct method is invoked based on the input parameters.
It is important to remember that method overloading is not based on return type alone. The parameters must differ in type, number, or both. Here's an example:
class Calculator {
// Method with int return type
public int add(int a, int b) {
return a + b;
}
// Method with double return type (not allowed for overloading by return type alone)
// public double add(int a, int b) { // This would cause a compile-time error
// return a + b;
// }
}
If you try to overload a method only by changing the return type, youβll encounter a compile-time error. The parameter list must be different.
Method overloading is not the same as method overriding. Overloading happens at compile time (static polymorphism), while overriding is a runtime behavior (dynamic polymorphism).
In method overloading, you define multiple methods with the same name but different parameters within the same class, while method overriding involves redefining a method of a superclass in a subclass with the same signature.
Quick Tip:
Method overloading improves readability and flexibility by allowing multiple methods with the same name but different parameters. Make sure to distinguish methods based on their parameter lists, not just their return types.
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!