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
Main
class, 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
sameName
methods has a different signature, which means they take different types of parameters. The first method takes twoint
parameters, the second method takes twoString
parameters, and the third method takes twodouble
parameters. -
Inside each method, we simply perform a simple arithmetic operation (
+
operator forint
anddouble
parameters) or concatenate theString
parameters with a space. -
In the
main
method, we call thesameName
methods 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
sameName
passes twoint
arguments (5
and10
) and returns anint
value (15
). This is printed to the console. -
The second call to
sameName
passes twoString
arguments ("asdas"
and"asdasda"
) and returns aString
value ("asdas asdasda"
). This is also printed to the console. -
The third call to
sameName
passes twodouble
arguments (5.0
and10.0
) and returns adouble
value (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.
No comments:
Post a Comment