# Protected members

protected members 保護成員，在先前的範例皆使用過公有public、私有private的成員，而在本篇將帶入 保護 protected 使用方式。

> *把成員宣告為 protected 的用處以及好處為：*
>
> * *父類別與子類別皆能使用*
> * *除 父、子類別之外就無法存取*
> * *不像 private 無法直接繼承至子類別，或透過公開函數來繼承*
> * *利用繼承，父類別中的 protected 可直接繼承至子類別*

改寫先前的範例來做示範：

先前 CCircle 父類別使用的為私有成員，因此子類別需要透過公有public 來存取private成員；

```
private static double pi=3.14;
private double radius;
```

改寫後如下：

```
class CCircle
{
   protected static double pi=3.14;   // 宣告為protected
   protected double radius;   // 宣告為protected

   public void show()
   {
      System.out.println("area="+pi*radius*radius);
   }
}
class CCoin extends CCircle   // 子類別 CCoin
{
   private int value;

   public CCoin(double r, int v)
   {
      radius=r;      // 直接取用父類別的protected成員
      value=v;
      System.out.println("radius="+radius+", value="+value);
   }
}
public class class04
{
   public static void main(String args[])
   {
      CCoin coin=new CCoin(2,10);
      coin.show();
   }
}
```

當main() 中，建立 coin 物件時，傳值呼叫子類別的「有引數的建構元」：

並直接設值至父類別的 radius 成員。

因此執行結果會先印出 radius=2, value=10

而呼叫 show 時，將會印出 area=12.56

我想，透過這樣的範例 protected 與 private 最大的差異就是其便利性了。

兩者同樣有不被外界任意更改與存取的用途；\
而在父子類別之間的運用，使用 protected 不僅安全也便利。


---

# 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-11/java-protected-members.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.
