# 函數多載

多載 (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);
	}

}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://java.4-x.tw/java-07/java-07-3.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
