Java Method Overloading
Syntax
// Method with no parameter
public void methodname() {...}
// Method with one parameter
public void methodname(type1 var1) {...}
// Method with multiple parameters
public void methodname(type1 var1, type2 var2, ...) {...}
Example
class Example {
public void method() {
System.out.println("This method has no parameters.");
}
public void method(int num) {
System.out.println("This method has one parameter: " + num);
}
public void method(String str, int num) {
System.out.println("This method has two parameters: " + str + " and " + num);
}
}
class Main {
public static void main(String[] args) {
Example obj = new Example();
obj.method();
obj.method(5);
obj.method("Hello", 7);
}
}
Output
This method has no parameters.
This method has one parameter: 5
This method has two parameters: Hello and 7
Explanation
Java method overloading allows us to have multiple methods with the same name but different parameters. This means that we can create methods with the same name, but with different input parameters.
In the above example, method()
has three versions with different parameters. The first method has no parameters, the second method has one integer parameter, and the third method has one string parameter and one integer parameter. When we call the different methods with different parameters, Java will determine which method to call based on the number and types of the parameters passed.
Use
Method overloading is used to provide different ways of calling methods that perform similar tasks. This makes the code more readable and improves the reusability of methods.
Important Points
- Method overloading allows us to create methods with the same name but different parameters.
- The methods must have different parameter types or different numbers of parameters.
- The return type of the method does not affect method overloading.
- Java determines which method to call based on the number and types of parameters passed.
Summary
Java method overloading is a powerful feature that allows us to create methods with the same name but different parameters. This makes the code more readable and improves the reusability of methods. When calling a method with overloaded methods, Java will determine which method to call based on the number and types of parameters passed.