JAVA中的方法過載以及可變引數程式設計
阿新 • • 發佈:2020-12-07
JAVA中的方法過載
- 過載解決的問題
- 過載的規則
- 過載的使用
- 可變引數程式設計
一、過載解決的問題
有時我們需要用一個函式,同時兼顧多種引數的情況。這時就需要用到方法的過載。
二、過載的規則
針對同一個類:
- 方法名相同
- 方法的引數不同(引數的個數或者引數的型別)
- 方法的返回值不做要求,不影響過載
三、過載的使用
程式碼如下:
public static int add(int a,int b){
return a + b;
}
public static double add(double a,double b){
return a + b;
}
public static int add(int a,int b,int c){
return a + b + c;
}
public static void main(String[] args) {
System.out.println(1 + 8);
System.out.println(3.0+8.8);
}
執行結果
************************錯誤示範*************************
public static int add (int a,int b){
return a + b;
}
public static double add(int a,int b){ //編譯出錯
return a + b;
}
執行結果
當兩個方法方法名相同,引數也相同,只有返回值不同時,不構成函式過載。
四、 可變引數程式設計
定義時,在最後一個形參後加上三點 …,就表示該形參可以接受多個引數值。且傳入的一組資料,本質上被編譯器看作一個數組。需要注意的是,這一組資料的資料型別必須相同。
public static int sum(int...array){
int ret = 0;
for(int x:array){
ret += x;
}
return ret;
}
public static void main(String[] args) {
System.out.println(sum(1,2,2));
System.out.println(sum(1,2,4,5,6,7));
}
執行結果
總結
我理解的是過載時=是幾個方法使用同一種思想,實現同一功能,只是需要傳入的引數不同。