# 認識 建構元

什麼是建構元，他的作用是什麼？

1. 建構元是一個類別中的功能，他會與類別名稱相同
2. 建立物件時，建構元將自動執行
3. 目的是用來設定初值

在[使用類別](https://java.4-x.tw/java-08/java-08-2)篇章提到如何建立類別的物件

> ```
> CRectangle book;
> book= new CRectangle();
> ```
>
> 也可以寫成一行
>
> ```
> CRectangle book=new CRectangle();
> ```

透過建構元的技術，我們可以直接在建立物件時設值

```
CRectangle book=new CRectangle(5);
```

以下為一簡單範例：

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

   public CCircle(double r)      // 在此定義建構元CCircle()
   {
      radius=r;
   }
   public void show()
   {
       System.out.println("radius="+radius+", 面積="+pi*radius*radius);
   }
}
public class class_constructor_1
{
   public static void main(String args[])
   {
      CCircle cir1=new CCircle(4.0); // 建立物件的同時，呼叫建構元設值
      cir1.show();
   }
}
```

建立建構元的方式很簡單，名稱與該類別相同即可

```
public CCircle(double r)      // 在此定義建構元CCircle()
{
   radius=r;
}
```

在主程式部分，建立物件的同時，也在呼叫建構元。

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

此刻便可直接設值給建構元

> 我們可以給建構元一個定義的格式：
>
> ```
> public/private 類別名稱(型態 引數)
> {
>   程式敘述;
>   ．．．．
> }
> ```
>
> 值得注意的是，建構元無回傳值


---

# 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-1.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.
