Explain Method Overloading in Java. Please give an example
Method overloading in Java is a feature that allows a class to have more than one method with the same name, but with different parameter lists. This means that you can define multiple methods that perform similar functions but take different types or numbers of parameters. The method to be executed is determined at compile time based on the method signature (the method name and the parameter list).
Here’s a simple example to illustrate method overloading in Java:
class MathOperations {
// Method to add two integers
int add(int a, int b) {
return a + b;
}
// Overloaded method to add three integers
int add(int a, int b, int c) {
return a + b + c;
}
// Overloaded method to add two double values
double add(double a, double b) {
return a + b;
}
}
public class Main {
public static void main(String[] args) {
MathOperations mathOps = new MathOperations();
// Calling the first add method
int sum1 = mathOps.add(5, 10); // Calls add(int, int)
System.out.println("Sum of two integers: " + sum1);
// Calling the second add method
int sum2 = mathOps.add(5, 10, 15); // Calls add(int, int, int)
System.out.println("Sum of three integers: " + sum2);
// Calling the third add method
double sum3 = mathOps.add(5.5, 10.5); // Calls add(double, double)
System.out.println("Sum of two doubles: " + sum3);
}
}
MathOperations
class has three overloaded add
methods:
Main
class, we create an instance of MathOperations
and call each of the overloaded add
methods with different arguments. The appropriate method is called based on the number and type of arguments passed.Sum of two integers: 15
Sum of three integers: 30
Sum of two doubles: 16.0
This demonstrates how method overloading allows for more flexible and readable code by using the same method name for similar operations that differ in their input parameters.