# 建構元中的公有與私有

讓我們再次複習一次上次帶入的觀念

> 公有與私有 ( public & private)：
>
> 1. 若冠上 public 公有的成員，可以被 其他程式自由的存取
> 2. 若冠上 private 私有的成員，除了 package 其他程式無法存取外，自身的程式也無法存取；運作的範圍只在該類別當中
> 3. 若省略 公有與私有 ( public & private) 都不使用，那麼成員只會在同一 package 存取使用

那麼建構元的公有私有：

同理，公有建構元可以在程式任何一處被呼叫；\
私有建構元無法在他所處的類別 之外的地方被呼叫。

讓我們看看 建構元的公有私有如何使用的：

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

   private CCircle()                   //私有建構元 無引數
   {
      System.out.println("私有建構元被呼叫");
   }
   public CCircle(String str, double r)   //公有建構元 兩個引數
   {
      this();
      color=str;
      radius=r;
   }
   public void show()
   {
      System.out.println("color="+color+", Radius="+radius);
      System.out.println("area="+pi*radius*radius);
   }
}
public class class_pp_2{
   public static void main(String args[])
   {
      CCircle cir1=new CCircle("Blue",1.0);
      cir1.show();
   }
}
```

讓我們開始解說以上的程式：

主程式呼叫了 擁有兩個引數的建構元

```
CCircle cir1=new CCircle("Blue",1.0);
```

而這個擁有兩個引數的建構元 為一個公有建構元，因此可以被呼叫

```
public CCircle(String str, double r)   //公有建構元 兩個引數
   {
      this();
      color=str;
      radius=r;
   }
```

看到這個公有建構元內，運用到了this()

可以參考： [建構元間的呼叫](/java-09/java-09-3.md) 這篇 this 的使用；

透過公有的建構元，使用this 來呼叫 私有的建構元：\
因此OUTPUT：

私有建構元被呼叫\
color=Blue, Radius=1.0\
area=3.14

## 注意

因為有兩個引數的建構元為公有的，因此以下寫法是正確的：

```
CCircle cir1=new CCircle("Blue",1.0);
```

但若是以下寫法就是錯誤的：

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

因為呼叫一個私有的建構元 （沒有引數的建構元），私有的建構元是無法在類別之外被呼叫的！


---

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