# super() 與 this()

super() 與 this() 兩者的功能有點類似，簡單比較一下兩者：

> *this：存取 本身類別 的成員（資料成員、函數成員、建構元）*
>
> *super：存取 父類別 的成員（資料成員、函數成員、建構元）*

在先前提到的 super() 是透過括號內引數來呼叫對應的父類別建構元；\
super 除了可以這麼做之外，super 也可以加上成員 的方式來呼叫。見以下範例：

```
class Caaa
{
   protected int num;

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

透過「 super . 父類別成員名稱」這樣的格式，就能呼叫父類別的成員。\
如以上範例中：

```
super.num=20;
super.show();
```

在main() 中，呼叫了子類別的函數 show()

* 透過super.num=20 設20給父類別的資料成員num
* 透過super.show() 來呼叫父類別的函數show()

因此本範例的執行結果為：\
Cbbb\_num=10\
Caaa\_num=20

[先前](https://scheng.tk/blog/1219/java-class-constructor-03)提過的 this 也是只有說明建構元間互相呼叫，\
this 也是可以透過 「 this . 本身類別的成員名稱」這樣的格式，來呼叫本身類別的成員。

將剛剛的範例加上 this 的示範：

```
class Caaa
{
   protected int num;

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

   public void show()
   {
      this.num=20;
      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();
   }
}
```

以上範例，多加了一個：

```
this.num=20;
```

在子類別中，有宣告一個資料成員 num=10，

透過 this.num 就會呼叫自己類別中的資料成員；\
所以本次範例的執行結果為：\
Cbbb\_num=20\
Caaa\_num=20

透過本篇，對 super 與 this 又多了新的認識，與使用方法～！


---

# 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-super-and-this.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.
