# 類別中函數的多載

在類別中，函數成員相同可以進行多載。

## 複習多載

多載 (overloading)

1. 函數名稱相同，引數個數不同
2. 引數型態不同，引數個數相同

> 相似功能的函數，以相同的名稱來命名之；透過不同的引數個數，或是不同的型態，\
> 來執行相對應的功能。

## 函數多載範例

以下範例為一個函數利用多載的技術所撰寫的：

```
class CCircle{
	String color;
	double pi=3.14;
	double radius;

	void setColor(String str){
		color=str;
		System.out.println("顏色＝ "+color);
	}
	void setRadius(double r){
		radius=r;
		System.out.println("半徑＝ "+radius);
	}
	void setAll(String str, double r){
		color=str;
		radius=r;
	}
	void show(){
		System.out.println("顏色＝ "+color+", 半徑＝ "+radius);
		System.out.println("面積＝ "+pi*radius*radius);
	}
}
public class ch08_4 {

	public static void main(String[] args) {
		CCircle cake=new CCircle();

		cake.setColor("粉紅");
		cake.setRadius(5);
		cake.setAll("藍色", 2);
		cake.show();
	}
}
```

雖然在主程式當中，呼叫類別函數成員時可以由名稱大略得知該函數的功能；\
但因為部分功能相近，我們可以透過多載的技術來整理：

將上面的範例中部分的函數拿出來整理，這三者共通點都為一個設定的條件（設定顏色、半徑、pi）

```
void setColor(String str)
void setRadius(double r)
void setAll(String str, double r)
```

改成相同的函數名稱；\
而在引數部分，除了型態不同之外，也有個數不同的引數

```
void setCircle(String str)
void setCircle(double r)
void setCircle(String str, double r)
```

如此一來只要在主程式呼叫函數時，就不需要記太多函數名稱，\
直接透過引數的型態不同，或是個數不同，\
就能呼叫相對應的類別函數成員。

```
cake.setCircle("粉紅");
cake.setCircle(5);
cake.setCircle("藍色", 2);
```

## 完整範例程式碼

```
class CCircle2{
	String color;
	double pi=3.14;
	double radius;

	void setCircle(String str){
		color=str;
		System.out.println("顏色＝ "+color);
	}
	void setCircle(double r){
		radius=r;
		System.out.println("半徑＝ "+radius);
	}
	void setCircle(String str, double r){
		color=str;
		radius=r;
	}
	void show(){
		System.out.println("顏色＝ "+color+", 半徑＝ "+radius);
		System.out.println("面積＝ "+pi*radius*radius);
	}
}
public class ch08_4_2 {

	public static void main(String[] args) {
		CCircle2 cake=new CCircle2();

		cake.setCircle("粉紅");
		cake.setCircle(5);
		cake.setCircle("藍色", 2);
		cake.show();
	}
}
```

## 注意

不能引數的個數與型態相同，只有函數成員的回傳型態不同。

ex.

```
void setCircle(double r)
int setCircle(double r)
```


---

# 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-08/java-08-7.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.
