- 方法重载概述
- 在同一个类中,允许存在一个以上的同名方法,只要它们的参数个数或者参数类型不同即可。
- 方法重载特点
- 与返回值类型无关,只看方法名和参数列表
- 在调用时,虚拟机通过参数列表的不同来区分同名方法
public class MethodDemo {
public static void main(String[] args) {
//定义两个变量
int a = 10;
int b = 20;
//求和
int result = sum(a,b);
System.out.println("result:"+result);
//定义变量
int c = 30;
//int result2 = sum2(a,b,c);
int result2 = sum(a,b,c);
System.out.println("result2:"+result2);
}
public static float sum(float a,float b) {
return a + b;
}
//求三个数据的和
public static int sum(int a,int b,int c) {
return a + b + c;
}
//求两个数据的和
public static int sum(int a,int b) {
return a + b;
}
}
2、方法重载练习之比较两个数据是否相等
需求:比较两个数据是否相等。
参数类型分别为两个byte类型,两个short类型,两个int类型,两个long类型,
并在main方法中进行测试
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));
}
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;
}
//两个int类型
public static boolean compare(int a,int b){
System.out.println("int");
return a == b;
}
//两个long类型
public static boolean compare(long a,long b){
System.out.println("long");
return a == b;
}
}



