Overloading in Java
Overloading in Java refers to the ability to define multiple methods with the same name but different parameter lists within a class. It allows the same method name to be used for different operations or actions depending on the type or number of arguments.
Example 1: Addition
Consider the following class with overloaded methods for addition:
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;
}
}
In this example, the Calculator
class has three methods named add
that perform addition. The methods are overloaded based on the number and type of parameters. By providing different parameter lists, we can use the same method name for different addition operations.
Example 2: Print Array
Consider another example where we overload a method to print different types of arrays:
class ArrayPrinter {
public void printArray(int[] arr) {
for (int num : arr) {
System.out.print(num + " ");
}
System.out.println();
}
public void printArray(String[] arr) {
for (String str : arr) {
System.out.print(str + " ");
}
System.out.println();
}
}
In this case, the ArrayPrinter
class has two methods named printArray
. One method accepts an integer array, while the other accepts a string array. This allows us to print arrays of different types using the same method name.
Some more example
public class Main {
public static void main(String[] args) {
Calculator calculator = new Calculator();
int sum1 = calculator.add(5, 10);
System.out.println("Sum 1: " + sum1);
double sum2 = calculator.add(3.5, 7.2);
System.out.println("Sum 2: " + sum2);
int sum3 = calculator.add(2, 4, 6);
System.out.println("Sum 3: " + sum3);
}
}
Output:
Sum 1: 15
Sum 2: 10.7
Sum 3: 12
Go To OOPS Page Click Here