方法重载指同一个类中定义的多个方法间的关系,满足下列条件的多个方法相互构成重载。(可以兼容不同的类型)
a)多个方法在同一个类中
b)多个方法具有相同的方法名
c)多个方法的参数不相同,参数类型不同或者参数数量不同。
与返回值无关,调用的时候,java虚拟机通过参数不同来区分同名的方法。
重载练习:
public class MethodTest {
public static void main(String[] args) {
System.out.println(compare(10,20));
System.out.println(compare((byte) 10,(byte) 10));
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;
}
}