Curriculum
Function overloading in Java refers to the ability to define multiple methods with the same name in a class, but with different parameters. Each method with the same name should have a unique set of parameters, so that the Java compiler can distinguish between them and call the appropriate method based on the arguments passed to it.
Function overloading allows you to reuse the same method name to perform different tasks or operations with different types or number of parameters, making your code more concise and easier to read. It is a form of polymorphism in Java, which allows objects of different types to be treated as if they were of the same type.
Here’s an example of function overloading in Java:
public 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 defines three methods with the same name “add”, but with different parameter lists. The first method takes two integer parameters and returns their sum as an integer, the second method takes two double parameters and returns their sum as a double, and the third method takes three integer parameters and returns their sum as an integer.
When you call the “add” method with different arguments, the Java compiler determines which method to call based on the number and types of the arguments passed to it. For example:
Calculator calculator = new Calculator(); int result1 = calculator.add(2, 3); // calls the first add method and returns 5 double result2 = calculator.add(2.5, 3.5); // calls the second add method and returns 6.0 int result3 = calculator.add(2, 3, 4); // calls the third add method and returns 9
Here, the first call to “add” method passes two integer parameters, so the first “add” method is called and returns an integer result. The second call to “add” method passes two double parameters, so the second “add” method is called and returns a double result. The third call to “add” method passes three integer parameters, so the third “add” method is called and returns an integer result.
Function overloading is a powerful feature of Java that allows you to create more flexible and expressive code, and can be used to implement a variety of operations and behaviors in your classes. However, it’s important to keep the method names and parameter lists distinct and unambiguous, to avoid confusion and errors in your code.