# 類別變數

> 類別變數：物件共享，佔用在同一個記憶體
>
> 類別函數：可以直接呼叫

如何宣告為類別變數：

加上 static 就可以定義為類別變數

帶入範例：

```
class CCircle
{
   private static int count=0;         //宣告為類別變數
   private static double pi=3.14;      //宣告為類別變數
   private double radius;

   public CCircle()        // 建構元 沒有引數
   {
      this(1.0);           // 呼叫一個引數的建構元 並給值
   }
   public CCircle(double r)   // 建構元 一個引數
   {
      radius=r;
      count ++;               // 呼叫到此建構元就加一
   }
   public void show()
   {
      System.out.println("area="+pi*radius*radius);
   }
   public void show_count()   // 用來顯示建立物件的個數
   {
      System.out.println(count+" 個物件被建立");
   }
}
public class instance_vs_class_02
{
   public static void main(String args[])
   {
      CCircle cir1=new CCircle();      //呼叫沒有引數的建構元
      cir1.show_count();     // 呼叫顯示個數的函數
      CCircle cir2=new CCircle(2.0);   //呼叫一個引數的建構元
      CCircle cir3=new CCircle(4.3);   //呼叫一個引數的建構元
      //以下使用物件呼叫顯示個數的函數
      cir1.show_count();
      cir2.show_count();
      cir3.show_count();
   }
}
```

宣告類別變數

```
private static int count=0;         //宣告為類別變數
private static double pi=3.14;      //宣告為類別變數
```

在主程式呼叫沒有引數的建構元，並顯示目前的物件個數

```
CCircle cir1=new CCircle();      //呼叫沒有引數的建構元
cir1.show_count();     // 呼叫顯示個數的函數
```

各別再建立物件 cir2 和 cir3，呼叫有一個引數的建構元：

```
CCircle cir2=new CCircle(2.0);   //呼叫一個引數的建構元
CCircle cir3=new CCircle(4.3);   //呼叫一個引數的建構元
```

最後再呼叫顯示個數的函數，做測試：

```
cir1.show_count();
cir2.show_count();
cir3.show_count();
```

再OUTPUT 部分：\
第一次因為只有建立一個 cir1 的物件，因此呼叫顯示個數的函數會顯示：1個物件被建立；

各別又建立物件 cir2 和 cir3 之後，\
呼叫顯示個數的函數皆會顯示 3個物件被建立。

因為 count 宣告為類別變數，因此三個物件將會共同使用它

```
private static int count=0;
```


---

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