Java 方法成員多載 (Method Overloading) 範例:
class JCRectArea {
private int height, wide;
JCRectArea(){
height = wide = 1;
}
JCRectArea(int h){
SetHeight(h);
wide = 1;
}
JCRectArea(int h, int w){
SetHeight(h);
SetWide(w);
}
void SetHeight(int h){
height = h;
}
void SetWide(int w){
wide = w;
}
int GetArea(){
return height*wide;
}
}
public class JConstructor {
public static void main(String[] args){
JCRectArea a1 = new JCRectArea();
System.out.println("AREA ="+a1.GetArea());
JCRectArea a2 = new JCRectArea(5);
System.out.println("AREA ="+a2.GetArea());
JCRectArea a3 = new JCRectArea(3,6);
System.out.println("AREA ="+a3.GetArea());
}
}
輸出:
50+10=60
-10.99+4.11=-6.88
說明:
Java 所提供的方法成員多載(Method Overloading)允許程式設計師使用相同的方法名稱命名,在傳統的程式語言中方法(或稱函數)只要參數中的個數或型態不同就必需要獨立使用不同的方法名稱,因此造成許多設計上的不便,上頭為兩數交換的程式會使用相同的Add()方法名稱,而Java會自動針對所使用的參數個數及型態去判斷並執行所對應的方法。


0 意見:
張貼意見