Java學習隨筆——方法過載
方法過載的簡單介紹
//參考資料來自網站:https://www.bilibili.com/video/BV1Rx411876f?p=98
方法即為C語言中的函式。
方法過載的引入
我們先來看下面的例子:
public class Test01 { public static void main(String[] arge) { int result1=sumInt(10,20); System.out.println(result1); double result2=sumDouble(10.0,20.0); System.out.println(result2);long result3=sumLong(10L,20L); System.out.println(result3); } public static int sumInt(int a,int b) { return a + b; } public static double sumDouble(double a,double b) { return a + b; } public static long sumLong(long a,long b) { returna + b; } }
執行結果為:
30 30.0 30
從上面的結果不難看出:
1、sumInt、sumDouble和sumLong三個為不同的方法,但處理內容相似都是求和。
2、功能相似的方法,分別啟了三個不同的名字,對於程式設計師來說,難以記憶。
3、程式碼不美觀。
功能雖然不同,但是功能相似的時候,有沒有這樣一種機制,可以讓程式設計師使用這些方法的時候就像在使用一個方法一樣,這樣程式設計師以後編 寫程式碼比較方便,也不需要記憶更多的方法名,程式碼也會很美觀。這樣的方法就叫做過載/overlord
方法過載
對上面的例子用過載的姿勢來一次,程式碼如下:
publicclass overlord01 { public static void main(String[] arge) { System.out.println(sum(10,20)); System.out.println(sum(10.0,20.0)); System.out.println(sum(10L,20L)); } public static int sum(int a,int b) { System.out.println("sum(int,int)"); return a + b; } public static double sum(double a,double b) { System.out.println("sum(double,double)"); return a + b; } public static long sum(long a,long b) { System.out.println("sum(long,long)"); return a + b; } }
執行後結果如下
sum(int,int) 30 sum(double,double) 30.0 sum(long,long) 30
從此可以輕鬆看出:
1、程式設計師在使用過載呼叫方法時,呼叫的方法名相同,就感覺在使用一個方法一樣。但本質上屬於不同的方法。
2、程式設計師不需要記憶更多的方法名。
3、程式碼變得美觀。
過載的使用方法
什麼時候需要使用過載呢?
方法實現的功能相似的時候使用,儘可能讓方法名相同。(注:功能不同/不相似的時候,不要讓方法名不同。)
過載具體呼叫哪個方法呢?
對應呼叫的方法根據引數資料型別進行判斷。如在程式overlord01程式中,sum(10,20)中,引數型別為int型,對應呼叫的方法為public static sum(int a,int b)。同理sum(10.0,20.0)中引數型別為double,對應呼叫的方法為public static sum(double a,double b)。
滿足什麼條件構成了方法的過載?
1.在同一個類中
2.方法名相同
3。引數列表不同:
-數量不同
-順序不同
-型別不同
結合上面的介紹,請各位判斷一下下面哪些可以構成過載,哪些不能
public class overlord02 { public static void test(){} public static void test(int a){} public static void test1(int a ,double b){} public static void test1(double b,int a){} public static void test2(int x){} public static void test2(double y){} public static void test3(int a,int b){} public static void test3(int b,int a){} public static void test4(){} public static int test4(){} void test5(){} public static void test5(){} }
...
...
...
...
...
...
答案如下,你答對了嗎?
public class overlord02 { //可以過載 public static void test(){} public static void test(int a){} //可以過載 public static void test1(int a ,double b){} public static void test1(double b,int a){} //可以過載 public static void test2(int x){} public static void test2(double y){} //不可以過載 public static void test3(int a,int b){} public static void test3(int b,int a){} //不可以過載 public static void test4(){} public static int test4(){} //不可以過載 void test5(){} public static void test5(){} }
過載與什麼有關係,和什麼沒關係?
1、方法過載與方法名和引數列表有關係
2、方法過載與返回值型別無關
3、方法過載與修飾符列表無光
如有錯誤歡迎指出