---
# System prepended metadata

title: '[Java] 類別(2) 談函數的多載'
tags: [多載, Java, 函數]

---

# [Java] 類別(2) 談函數的多載
###### tags: `Java` `函數` `多載`

---

```java=
class Car        // 定義類別CCircle
{
	int age;
	String brand;
	void set_age(int r) {
		age = r;
	}
	void set_brand(String s) {
		brand = s;
	}
	public void show_all() {
		System.out.println("Brand is " + brand + ", Age is "+age);
	}
}


public class app2_1
{
   public static void main(String args[])
   {
		   Car cir = new Car();
		   cir.set_age(5);
		   cir.set_brand("benz");
		   cir.show_all();
		   
   }
}
```
output:
Brand is benz, Age is 5

---

此篇為下一篇建構元的前言
此篇先討論何謂函數的多載
上方例子透過set_age() method和set_brand()method來分別設定age和brand的值

---

```java=
class Car
{
	int age;
	String brand;
	void set(int r) {
		age = r;
	}
	void set(String s) {
		brand = s;
	}
	public void show_all() {
		System.out.println("Brand is " + brand + ", Age is "+age);
	}
}

public class app2_1
{
   public static void main(String args[])
   {
		   Car cir = new Car();
		   cir.set(5); // 為整數型別的參數，因此會呼叫void set(int r)
		   cir.set("benz"); // 為字串型別的參數，因此會呼叫void set(String s)
		   cir.show_all();
   }
}
```
output:
Brand is benz, Age is 5


---

透過函數的多載，利用參數不同的型別去呼叫不同的函數成員

