相同點:
都是在同一類裡的一些同名,不同參數的方法形成重載。
都會出現參數傳遞時類型匹配的二義性匹配問題:
add(1,2) ;public void add(double a, float b) {...}public void add(float a, double b) {...}
不同點:
對於C++來說重載還可以發生在相同參數的const與非const版本之間,但是java不行對於java來說相同參數的final和非final版本函數不會構成重載。(編譯器會報錯)
public void xx1(int a) { ... } public void xx1(final int c) { ... } /* these are not overload methods, the xx1 is repeaed defined */
對於可變參數
public void test (String msg) {...}public void test (String... msgs) {...}obj.test("Tom") ; /* there call the firest test *//* follow call the second test */obj.test("Evan, Tank) ;obj.test() ;
可以看出只有與非可變參數的方法完全符合才會調用此方法,否則都會調用可變參數的。
可變參數方法重載引出的二義性問題
public void go(int ... nums) {...} /* at least has 0 parameter */public void go(int a, int... nums) {...} /* at least has 1 parameter */public void go(int a, int b, int... nums) {...} /* at least has 2 parameters */ obj.go(1) ; /* can be called by firest and second method */ obj.go(1,2); /* can be called by 1st,2nd,3th methods */obj.go(1,2,3) ; /* can be called by 1st, 2nd, 3th methods */
上面的3個go來說它們的區別在於對最小參數個數的限制,如果一個調用他傳遞的參數的個數>=兩個以上的重載函數,那麼對於這個調用來說滿足他的參數的重載方法都是他的首選,從而可能出現二義性問題。如上面的obj.go(1) 對於他來說第一個和第二個方法均是首選從而導致編譯時間的二義性。