Q.
Explain method overloading with suitable example
Method Overloading in Java
Method Overloading in Java occurs when multiple methods have the same name but differ in
parameters (number, type, or both) within the same class. The return type can be different, but it
alone cannot be used to distinguish overloaded methods. Overloading allows a class to have
more than one method with the same name but performing different tasks based on the
parameters passed to them.
Key Points of Method Overloading:
1. Same Method Name: Overloaded methods must have the same name.
2. Different Parameters: The methods must differ in the number or type of parameters.
3. Return Type: The return type can be different, but it is not enough to distinguish overloaded
methods. The parameters must differ.
Advantages of Method Overloading:
Increases the readability of the program.
Allows for flexibility, as methods can perform the same task but with different input types or
number of arguments.
---Example of Method Overloading:
public class MethodOverloadingExample {
// Method to add two integers
public int add(int a, int b) {
return a + b; }
// Overloaded method to add three integers
public int add(int a, int b, int c) {
return a + b + c; }
// Overloaded method to add two double values
public double add(double a, double b) {
return a + b; }
// Main method to test the overloaded methods
public static void main(String[] args) {
MethodOverloadingExample obj = new MethodOverloadingExample();
// Calling the method with two integer arguments
System.out.println("Sum of two integers: " + obj.add(10, 20));
// Calling the method with three integer arguments
System.out.println("Sum of three integers: " + obj.add(10, 20, 30));
// Calling the method with two double arguments
System.out.println("Sum of two doubles: " + obj.add(10.5, 20.5)); }}
Explanation:
The class MethodOverloadingExample contains three add methods.
1. The first add method takes two integers and returns their sum.
2. The second add method takes three integers and returns their sum.
3. The third add method takes two double values and returns their sum.
The main method creates an object of the class and calls the overloaded add methods with
different types and numbers of parameters.
Output:
Sum of two integers: 30
Sum of three integers: 60
Sum of two doubles: 31.0