Method overloading in Java is a feature that allows a class to have multiple methods with the same name, but with different parameters. This means that you can define two or more methods with the same name in a class, as long as they have different parameter lists.
In method overloading, the compiler determines which version of the method to use based on the number, types, and order of the arguments passed to it. When you call an overloaded method, the compiler chooses the appropriate method to execute based on the arguments you pass to it.
public class Main {
public static int sameName(int x, int y) {
return x + y;
}
public static String sameName(String x, String y) {
return x + " " + y;
}
public static double sameName(double x, double y) {
return x + y;
}
public static void main(String[] args) {
System.out.println(sameName(5, 10));
System.out.println(sameName("asdas", "asdasda"));
System.out.println(sameName(5.0, 10.0));
}
}
Here's an explanation of the code block by block:
- We begin with defining a Java class called
Main:
public class Main {
- Inside the
Mainclass, we define three static methods with the same namesameName:
public static int sameName(int x, int y) {
return x + y;
}
public static String sameName(String x, String y) {
return x + " " + y;
}
public static double sameName(double x, double y) {
return x + y;
}
-
Each of the
sameNamemethods has a different signature, which means they take different types of parameters. The first method takes twointparameters, the second method takes twoStringparameters, and the third method takes twodoubleparameters. -
Inside each method, we simply perform a simple arithmetic operation (
+operator forintanddoubleparameters) or concatenate theStringparameters with a space. -
In the
mainmethod, we call thesameNamemethods with different arguments and print the returned results:
System.out.println(sameName(5, 10));
System.out.println(sameName("asdas", "asdasda"));
System.out.println(sameName(5.0, 10.0));
-
The first call to
sameNamepasses twointarguments (5and10) and returns anintvalue (15). This is printed to the console. -
The second call to
sameNamepasses twoStringarguments ("asdas"and"asdasda") and returns aStringvalue ("asdas asdasda"). This is also printed to the console. -
The third call to
sameNamepasses twodoublearguments (5.0and10.0) and returns adoublevalue (15.0). This is also printed to the console.
In summary, this code demonstrates how method overloading works in Java by defining multiple methods with the same name but different parameter types, and then calling them with different arguments to perform different tasks.