java中方法重載什么?
方法重載是指一個類中可以有多個方法具有相同的名字,但這些方法的參數(shù)必須不同。好處:只需要記住唯一一個方法名稱,就可以實(shí)現(xiàn)類似的多個功能。
這里需要注意的是參數(shù)不同需要滿足2個條件,一個是參數(shù)的個數(shù)不同,一個是參數(shù)個數(shù)相同,但參數(shù)列表中對應(yīng)的某個參數(shù)的類型不同。
方法的重載與下列因素相關(guān):
1、參數(shù)個數(shù)不同
2、參數(shù)類型不同
3、參數(shù)的多類型順序不同
方法的重載與下列因素?zé)o關(guān):
1、與參數(shù)的名稱無關(guān)
2、與方法的返回值類型無關(guān)
例子:
題目要求:比較兩數(shù)據(jù)是否相等。
參數(shù)類型分別為兩個byte類型、兩個short類型、兩個int類型、兩個long類型。
并在main方法中進(jìn)行測試
public class CaiNiao{ public static void main(String[] args){ byte a = 10; byte b = 20; System.out.println(isSame(a,b)); System.out.println((isSame(short)20,(short)20)); System.out.println(isSame(11,22)); System.out.println(isSame(10L,10L)); } public static boolean isSame(byte a,byte b){ System.out.println("兩byte參數(shù)的方法執(zhí)行!"); boolean same ; if(a==b){ same = true; }else{ same = false; } return same; } public static boolean isSame(short a,short b){ System.out.println("兩short參數(shù)的方法執(zhí)行!"); boolean same = a == b ?true:false; return same; } public static boolean isSame(int a,int b){ System.out.println("兩int參數(shù)的方法執(zhí)行!"); return a == b:; } public static boolean isSame(long a,long b){ System.out.println("兩long參數(shù)的方法執(zhí)行!"); if (a==b){ return true; } else{ return false; } } }