Comment on page
函數多載
多載 (overloading)
- 1.函數名稱相同,引數個數不同
- 2.引數型態不同,引數個數相同
相似功能的函數,以相同的名稱來命名之;透過不同的引數個數,或是不同的型態,
來執行相對應的功能。
首先在主程式分別宣告不同資料型態的變數a、b、c、d
int a=2, b[]={1,2,3};
float c=3;
double d=3.14;
建立四個相同名稱的函數 show,引數個數同為一個,而型態不同
public static void show(int i)
public static void show(int arr[])
public static void show(float i)
public static void show(double i)
因此當在主程式呼叫函數時,將會執行相對應之型態的函數;
舉例來說:
show(a) ; a 為整數型態 int ,因此將會對應到引數為整數型態的函數
public static void show(int i)
show(b) ; b為整數型態的陣列,因此對應到引數為陣列整數型態的函數
public static void show(int arr[])
public class ch07_9 {
public static void main(String[] args) {
int a=2, b[]={1,2,3};
float c=3;
double d=3.14;
show(a);
show(b);
show(c);
show(d);
}
public static void show(int i){
System.out.println("值(a)="+i);
}
public static void show(int arr[]){
System.out.print("值(b)=");
for(int i=0;i<arr.length;i++)
System.out.print(arr[i]+" ");
}
public static void show(float i){
System.out.println("\n值(c)="+i);
}
public static void show(double i){
System.out.println("值(d)="+i);
}
}
這次在主程式直接呼叫函數,並設值。
show();
show(3);
show('A',5);
在函數的部分,擁有相同名稱卻有不同個數的引數:
public static void show( ) //無引數
public static void show(int n) //一個引數
public static void show(char ch,int n) //兩個引數
透過引數個數的不同,對應到應該呼叫的函數
public class ch07_9_2 {
public static void main(String[] args) {
show();
show(3);
show('A',5);
}
public static void show(){
System.out.println("no");
}
public static void show(int n){
for(int i=0;i<n;i++)
System.out.print("*");
System.out.println("");
}
public static void show(char ch,int n){
for(int i=0;i<n;i++)
System.out.print(ch);
}
}
Last modified 3yr ago