# 建構元的多載

先前提過函數的多載、類別函數成員的多載，相信也都要熟悉什麼是多載。\
在此再次說明多載是什麼：

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

以下範例為建構元利用多載的技術所撰寫的：

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

   public CCircle()                    // 這是一個沒有引數的建構元
   {
      System.out.println("constructor CCircle() called");
      color="Green";
      radius=1.0;
   }
   public CCircle(String str, double r)      // 這是一個有兩個引數的建構元
   {
      System.out.println("constructor CCircle(String,double) called");
      color=str;
      radius=r;
   }
   public void show()
   {
      System.out.println("color="+color+", Radius="+radius);
      System.out.println("area="+pi*radius*radius);
   }
}
public class class_constructor_2
{
   public static void main(String args[])
   {
      CCircle cir1=new CCircle();         // 建立物件
      cir1.show();

      CCircle cir2=new CCircle("Blue",4.0);  // 建立物件，並設兩個值
      cir2.show();
   }
}
```

在主程式方面可以了解以下事情：

若在建立物件的過程中：無設值，將會自動對應到沒有引數的建構元

```
CCircle cir1=new CCircle();
```

若在建立物件的過程中：設定兩個值，將會對應到有兩個引數的建構元

```
CCircle cir2=new CCircle("Blue",4.0);
```

在[使用類別](/java-08/java-08-2.md)篇章提到如何建立類別的物件；

同樣的概念：建立物件時，會呼叫建構元；若想要呼叫沒有引數的建構元，則不需設值；\
若想呼叫有引數的建構元，在建立的過程中 也必須設初值。

這就是為什麼建構元擁有設定初值的功能。

(詳見：[認識 建構元](/java-09/java-09-1.md))


---

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