方法的重載
對於功能類似的方法來說,因為參數列表不一樣,卻需要記住那多不同的方法名稱,太麻煩。
方法的重載(Overload):多個方法的名稱一樣,但是參數列表不一樣。
好處:只需要記住唯一一個方法名稱,就可以實現類似的多個功能。
方法的重載與下列因素相關:
- 參數個數不同
- 參數類型不同
- 參數的多類型順序不同
方法的重載與下列因素無關:
- 與參數的名稱無關
- 與方法的返回值類型無關
例子:
題目要求:
比較兩數據是否相等。
參數類型分別為兩個byte類型、兩個short類型、兩個int類型、兩個long類型。
並在main方法中進行測試
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參數的方法執行!"); boolean same ; if(a==b){ same = true; }else{ same = false; } return same; }
public static boolean isSame(short a,short b){ System.out.println("兩short參數的方法執行!"); boolean same = a == b ?true:false; return same; } public static boolean isSame(int a,int b){ System.out.println("兩int參數的方法執行!"); return a == b:; } public static boolean isSame(long a,long b){ System.out.println("兩long參數的方法執行!"); if (a==b){ return true; } else{ return false; } } }