java语言的方法的重载
1.什么是方法的重载
- 什么是重载
- 在同一个类中,有多个重名的方法。
- 组成规则
- 必须在同一个类中
- 方法名必须相同
- 参数列表必须不同
- 参数的数据类型不同
- 参数的数量不同
- 参数的顺序不同
- 与
- 返回值类型无关
- 示例代码
-
public class MethodDemo {
public static void main(String[] args) {
//调用方法
int result = sum(10,20);
System.out.println(result);double result2 = sum(10.0,20.0); System.out.println(result2); int result3 = sum(10,20,30); System.out.println(result3);
}
//需求1:求两个int类型数据和的方法
public static int sum(int a, int b) {
return a + b;
}//需求2:求两个double类型数据和的方法
public static double sum(double a, double b) {
return a + b;
}//需求3:求三个int类型数据和的方法
public static int sum(int a, int b, int c) {
return a + b + c;
}
}
2. 方法重载的练习-比较不同数据类型整数是否相等
```java
public class MethodTest {
public static void main(String[] args) {
//调用方法
System.out.println(compare(10, 20));
System.out.println(compare((byte) 10, (byte) 20));
System.out.println(compare((short) 10, (short) 20));
System.out.println(compare(10L, 20L));
}
//int
public static boolean compare(int a, int b) {
System.out.println("int");
return a == b;
}
//byte
public static boolean compare(byte a, byte b) {
System.out.println("byte");
return a == b;
}
//short
public static boolean compare(short a, short b) {
System.out.println("short");
return a == b;
}
//long
public static boolean compare(long a, long b) {
System.out.println("long");
return a == b;
}
}