Method Overloading
Java Method Overloading is a feature in Java that allows developers to define multiple methods with the same name in the same class, but with different parameters. This allows developers to create methods with the same name that can perform different tasks based on the data passed into them.
Method overloading is achieved by changing the method signature, which includes the method name and parameter list. When calling an overloaded method, the compiler determines which method to call based on the number, type, and order of the arguments passed to the method.
Here's an example code that demonstrates method overloading in Java:
public class Calculator {
public int add(int num1, int num2) {
return num1 + num2;
}
public double add(double num1, double num2) {
return num1 + num2;
}
public int add(int num1, int num2, int num3) {
return num1 + num2 + num3;
}
public static void main(String[] args) {
Calculator calc = new Calculator();
System.out.println("2 + 3 = " + calc.add(2, 3));
System.out.println("2.5 + 3.5 = " + calc.add(2.5, 3.5));
System.out.println("1 + 2 + 3 = " + calc.add(1, 2, 3));
}
}
In the above code, the Calculator class defines three methods named add, but with different parameter lists. The first method takes two integers and returns their sum, the second method takes two doubles and returns their sum, and the third method takes three integers and returns their sum.
In the main method, the Calculator class is instantiated and the add method is called three times with different arguments. The compiler determines which version of the add method to call based on the number and types of arguments passed.
This is a simple example of how method overloading works in Java. By using method overloading, developers can create more flexible and versatile classes that can handle a wider range of data types and parameters.
No comments:
Post a Comment