Method Overloading:
Method overloading in Java is a feature that allows you to define multiple methods with the same name but with different parameters within the same class. The methods can have the same name as long as the number or type of parameters in the method signature is different.
When you call an overloaded method, Java determines which version of the method to execute based on the arguments you pass. The decision is made at compile-time, and the appropriate method is called based on the matching parameter types.
Here's an example to illustrate method overloading in Java:
javapublic class MyClass {
public void printMessage() {
System.out.println("No arguments provided.");
}
public void printMessage(String message) {
System.out.println("Message: " + message);
}
public void printMessage(int number) {
System.out.println("Number: " + number);
}
public void printMessage(String message, int number) {
System.out.println("Message: " + message + ", Number: " + number);
}
public static void main(String[] args) {
MyClass obj = new MyClass();
obj.printMessage(); // Calls printMessage() without arguments
obj.printMessage("Hello, world!"); // Calls printMessage(String message)
obj.printMessage(42); // Calls printMessage(int number)
obj.printMessage("Hello", 42); // Calls printMessage(String message, int number)
}
}
In the example above, the MyClass
class contains several overloaded methods named printMessage
. These methods differ in the number and type of their parameters. The printMessage
method without any arguments is called when no arguments are provided. The appropriate method is chosen based on the arguments provided at the call site.
Method overloading allows you to provide different ways of using a method, making the code more readable and flexible. It's important to note that only the method signature (name and parameter types) is considered when overloading methods; the return type does not play a role in determining which method to call.
0 Comments