overloading in java
时间: 2023-10-17 21:22:05 浏览: 83
Java中的方法重载(overload).docx
In Java, method overloading refers to the ability to define two or more methods with the same name in a class. The methods must have different parameter lists (i.e., different types or different numbers of parameters). This allows us to use the same method name for different behaviors, depending on the type or number of parameters passed to it.
For example, we can define a method called "sum" that takes two integer parameters and returns their sum. We can also define another method called "sum" that takes three integer parameters and returns their sum. When we call the "sum" method, Java will automatically choose the appropriate method based on the number and types of parameters passed to it.
Here's an example of method overloading in Java:
```
public class OverloadingExample {
public static void main(String[] args) {
int a = 5, b = 10, c = 15;
double x = 2.5, y = 3.5;
System.out.println(sum(a, b)); // calls sum(int, int)
System.out.println(sum(a, b, c)); // calls sum(int, int, int)
System.out.println(sum(x, y)); // calls sum(double, double)
}
public static int sum(int a, int b) {
return a + b;
}
public static int sum(int a, int b, int c) {
return a + b + c;
}
public static double sum(double a, double b) {
return a + b;
}
}
```
In this example, we have three "sum" methods with different parameter lists. When we call the "sum" method with two integers, Java will call the first method that takes two integers. When we call the "sum" method with three integers, Java will call the second method that takes three integers. When we call the "sum" method with two doubles, Java will call the third method that takes two doubles.
阅读全文