# 設定終止繼承

在父類別中，有不希望被子類別繼承的成員 可以加上final 來終止繼承。\
若父類別中的函數成員加上 final ，子類別也就無法改寫（overriding）。

* 宣告為 final 後的變數，如同常數一般，無法再被更改
* 函數宣告 final後，無法改寫（overriding）
* 類別亦可宣告 final，如此一來就沒有子類別可以繼承

修改 [super與this 文章中](/java-11/java-super-and-this.md)的範例，來做本篇的示範：

```
final class Cfinal
{
	public void show()
	{
		System.out.println("Cfinal 父類別");
	}
}
class Ctest extend Cfinal
{
	public void show()
	{
		System.out.println("Ctest 子類別");
	}
}

class Caaa
{
   protected final int num=10;

   public final void show()
   {
      System.out.println("Caaa_num="+num);
   }
}
class Cbbb extends Caaa
{
   int num=10;

   public void show()
   {
      super.num=20;
      System.out.println("Cbbb_num="+num);
      super.show();
   }
}

public class supervsthis
{
   public static void main(String args[])
   {
      Cbbb b=new Cbbb();
      b.show();
   }
}
```

於本次範例有幾個點注意的部分：

* 將父類別 Cfinal 經過 final 宣告，因此底下的子類別 Ctest 是無法繼承父類別的

  ```
  class Ctest extend Cfinal
  ```
* 再看到另一個父類別 Caaa 中，

  ```
  protected final int num=10;

  public final void show()
  {
        System.out.println("Caaa_num="+num);
  }
  ```

  分別有 資料成員 num 與函數show() 經過 final 宣告，\
  因此在子類別 Cbbb 就無法正常繼承來自父類別的 num 或是 改寫父類別的 show() 函數
* 另外在 num 部分，若一變數想要經過 final 宣告，必須給訂一個值；\
  使之變成像常數一般，無法更改。

  ```
  protected final int num=10;
  ```

  常見範例如：

  ```
  protected final double PI=3.1415;
  ```

  如此一來，程式任何一處將不會更改到 PI 值。


---

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