# 認識抽象類別

抽象類別如同父類別一般，透過本篇了解 抽象類別的用法 及 抽象類別與父類別的不同處。

抽象類別 abstract class 的用法像「範本」一樣，我們可以依照其格式修改後運用之；\
如範本一般，因此無法直接使用：也就是說，我們不能直接透過 抽象類別 來建立物件。

一個簡單的整理：

* 抽象類別 不能用來建立物件
* 抽象函數 不定義其處理方式

進入範例之前，先了解一下 抽象類別 的格式：

```
abstract class 類別名稱
{
  宣告資料成員;
  /*
  傳回值資料型態 函數名稱(引數...)
  {
  ...
  } 定義一般的函數*/

  修飾子 abstract 傳回值資料型態 函數名稱(引數...);
  //抽象函數並無定義處理方式
}
```

有了以上基礎觀念後，先簡單帶入例子了解；\
先前提過改寫 overriding 的觀念，是用來改寫父類別中的函數。\
抽象函數也是這樣的動作，不過這次是直接不敘述函數的處理方式。

有許多種幾何形狀，都有顏色的屬性 並且都需要有一個show 函數 印出該顏色與面積；\
那麼我們可以設計一個抽象類別為 「形狀」，並且有一般函數用來設定顏色，\
一個只定義名稱的 抽象函數 來供子類別繼承使用：

```
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);
   }
}
```

CShape 被定義為一個抽象類別，其中有一個設定顏色的一般函數，與一個 抽象函數 show()。

CRectangle 為一矩形 子類別，除了擁有自己的資料成員 長寬 之外，\
也有一個建構元用來設定長與寬；

重點是： 有一個繼承來自 父類別的抽象函數 show()，並且有明確定義其敘述。

```
System.out.print("color="+color+",  ");
System.out.println("area="+width*height);
```

下一篇將透過完整範例做更加詳盡的解說，並加深對抽象類別 抽象函數 的使用。<br>


---

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