# 使用抽象類別型態的變數建立物件

在基本概念篇提到過，無法使用抽象類別直接建立物件，那麼是否有想過 有沒有其他方式呢？\
這篇就是要來談談這點，並且再提抽象類別的注意事項。

在 [overriding 篇](/java-11/java-overriding.md) 有提過，父類別變數可以用來存取子類別物件成員；\
在此處 抽象類別 一樣適用。

因此我們將上一篇 [範例：抽象類別](/java-12/java-12-2.md) 中的範例 main() 部分改成

```
public static void main(String args[])
   {
      CShape shape1=new CRectangle(5,10);
      shape1.setColor("Yellow");
      shape1.show();

      CShape shape2=new CCircle(2.0);
      shape2.setColor("Green");
      shape2.show();
   }
```

程式的執行結果也是會與上一篇的範例相同的：\
color=Yellow, area=50\
color=Green, area=12.56

以下為完整程式碼：

```
abstract class CShape               // 定義抽象類別 CShape
{
   protected String color;
   public void setColor(String str)    // 一般的函數
   {
      color=str;
   }
   public abstract void show(); // 只定義函數名稱的 抽象函數
}

class CRectangle extends CShape    // 子類別 矩形 CRectangle
{
   protected int width,height;
   public CRectangle(int w,int h)  //建構元
   {
      width=w;
      height=h;
   }
   public void show()      // 定義繼承而來的抽象函數 show() 的處理方式
   {
      System.out.print("color="+color+",  ");
      System.out.println("area="+width*height);
   }
}
class CCircle extends CShape     // 子類別 圓形CCircle
{
   protected double radius;
   public CCircle(double r)   //建構元
   {
      radius=r;
   }
   public void show()      // 定義繼承而來的抽象函數 show() 的處理方式
   {
      System.out.print("color="+color+",  ");
      System.out.println("area="+3.14*radius*radius);
   }
}
public class abstract_02
{
   public static void main(String args[])
   {
      CShape shape1=new CRectangle(5,10);
      shape1.setColor("Yellow");
      shape1.show();

      CShape shape2=new CCircle(2.0);
      shape2.setColor("Green");
      shape2.show();
   }
}
```

在 [overriding 篇](/java-11/java-overriding.md) 的文末，示範了使用父類別的陣列變數來存取子類別物件；\
我們可以將剛剛的abstract\_02範例，

```
CShape shape1=new CRectangle(5,10);
CShape shape2=new CCircle(2.0);
```

改成透過父類別陣列變數來存取：

```
CShape shape[];   //宣告陣列變數
shape=new CShape[2];
```

改成這樣有個好處是，如果物件數量一多，可以讓程式碼更有一致性：

![](/files/-MPaHP-UXZHnanCmDljg)

## 注意

最後要再次提醒，本篇是透過父類別變數方式來存取子類別物件成員；

抽象類別是不能直接建立物件的！

其原因也在於，抽象類別只定義名稱，並無定義處理方式；\
所以建立的物件會不曉得如何使用抽象類別中的抽象函數。

抽象類別中的抽象函數，子類別一定要改寫（overriding）之，\
其原因是定義後處理方式，物件才知道該如何運作。


---

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