方法重载:多个方法名称相同,但参数列表不同。
与以下因素有关:
1.参数个数不同;
运行结果为:
2.参数类型不同;
此时的运行结果为:
显示都是int类型,而我们其中有个要输出double类型才对,所以更改将数值写成 30.0 , 40.0 变成double类型即可。
此时运行的结果为:
3.参数的多类型顺序不同;
运行结果为:
与以下因素无关
1.与参数的名称无关:
显示报错,无法正常运行
2.与方法返回值类型无关;
显示报错,无法正常运行
练习:
习题:比较两个数据是否相等
参数类型分别为两个byte类型,两个int类型,两个short类型,两个long类型;
编辑程序是
public class demo {
public static void main(String[] args){
byte a=30;
byte b=40;
System.out.println(compare(a,b));
System.out.println(compare((short)a,(short) b));
System.out.println(compare(10,10));
System.out.println(compare(20L,20l));
}
public static boolean compare(byte a ,byte b){ //比较byte类型的大小
System.out.println("比较byte类型");
boolean same;
if(a==b) {
same = true;
}
else{
same = false;
}
return same;
}
public static boolean compare(int a ,int b){ //比较int类型的大小
System.out.println("比较int类型");
if(a==b) {
return true;
}
else{return false;}
}
public static boolean compare(short a ,short b){ //比较short类型的大小
System.out.println("比较short类型");
boolean same = a==b?true:false;
return same;
}
public static boolean compare(long a ,long b){ //比较long类型的大小
System.out.println("比较long类型");
return a==b;
}
}
运行结果为: