# 介面的延伸

前三篇從 帶入介面的觀念，到使用介面來達到多重繼承；而本篇則是要再將父子關係帶入介面！

介面也可以跟類別一樣，有 子介面 繼承 父介面。\
還有一點相同的是：也是使用 extends 關鍵字 來做介面的繼承。

與類別不同的是，介面可以繼承多個介面！

## 複習

介面 的格式：

```
interface 介面名稱
{
  final 資料型態 成員名稱=常數;

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

而介面的繼承也很簡單：

```
interface 子介面名稱 extends 父介面1名稱,父介面2名稱,...
{
  ...
}
```

讓我們透過實例了解本篇內容吧：將上一篇 [多重繼承](/java-13/java-13-3.md) 中的範例拿來本次改寫使用：

而這次 CShape 這個父介面的功能有資料成員PI 以及設定顏色的抽象函數 setColor()；\
CShape2D 則是用來顯示面積的用途。

![](/files/-MPaIw74smUz4r6WjH0n)

## 定義

### 父介面

```
interface CShape              //父介面 CShape
{
   final double PI=3.14;
   abstract void setColor(String str);
}
```

### 子介面繼承自父介面

```
interface CShape2D extends CShape  //CShape2D繼承父介面CShape
{
   abstract void area();
}
```

上方的介面繼承示意圖當中也有註明 extends 與 implements ，提醒實作介面時是使用implements。

另外在定義介面時，往往程式碼也是蠻簡潔的，\
因為重點都是寫在最後一個類別實作介面的敘述當中。

```
class CCircle implements CShape2D  //實作 CShape2D子介面
{
   double radius;
   String color;

   public CCircle(double r)
   {
      radius=r;
   }
   public void setColor(String str)
   {
      color=str;
      System.out.println("color="+color);
   }
   public void show()
   {
      System.out.println("area="+PI*radius*radius);
   }
}
```

另外可以注意到，CCircle 類別可以取用到 資料成員PI。\
原因是因為 CShape2D 繼承來自父介面的成員，因此類別實作子介面時也能取用到。

## 完整程式碼

```
interface CShape              //父介面 CShape
{
   final double PI=3.14;
   abstract void setColor(String str);
}

interface CShape2D extends CShape  //CShape2D繼承父介面CShape
{
   abstract void area();
}

class CCircle implements CShape2D  //實作CShape2D介面
{
   double radius;
   String color;

   public CCircle(double r)
   {
      radius=r;
   }
   public void setColor(String str)
   {
      color=str;
      System.out.println("color="+color);
   }
   public void show()
   {
      System.out.println("area="+PI*radius*radius);
   }
}
public class interface03
{
   public static void main(String args[])
   {
      CCircle moon=new CCircle(5.0);
      moon.setColor("yellow");
      moon.show();
   }
}
```


---

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