> For the complete documentation index, see [llms.txt](https://chihaolu.gitbook.io/all-in-one-solidity/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://chihaolu.gitbook.io/all-in-one-solidity/part-ii-medium/chapter-11-ji-cheng-inheritance/duo-chong-ji-cheng-yu-super.md).

# 【多重繼承與 super】

當一個合約從多個合約繼承時，在區塊鏈上只會有一個合約被建立，所有父合約的程式碼都被編譯到我們建立的子合約中。

在多重繼承的情況下 `super` 這個關鍵字在 Solidity 中可以調用最初的父合約。使用 `super` 的函數調用優先於大多數派生合約。

當我們擁有一個 contract A 並在其中有一個函數 `f()`，並且它的父合約之中也有一個函數 `f()`。此時 A 會覆寫（overrides）B 的 `f()`。這代表 `myInstanceOfA.f()` 會呼叫 A 之中的 `f()`，且 B 之中的 `f()` 將不可再被調用，但如果我們想要調用合約 B 的 `f()` 則可以再 A 之中使用 `super.f()`。

或者我們也可以顯式地（explicitly）宣告父合約的函數。以下是多重繼承的例子：

首先建立一個 c 合約，這個合約定義了一個變數 u。然後 b 合約去繼承 c 合約。這裡就不要定義變量了，使用的時 c 合約的變數。然後 a 合約繼承了 b 合約。

```solidity
pragma solidity ^0.8.11;

contract C {
  uint public u;
  function f() public virtual {
    u = 1;
  }
}

contract B is C {
  function f() public virtual override{
    u = 2;
  }
}

contract A is B {
  function f() public override{  // will set u to 3
    u = 3;
  }
  function f1() public { // will set u to 2
    super.f();
  }
  function f2() public { // will set u to 2
    B.f();
    // 使用 super 去呼叫的話，是呼叫 b 合約的，而不是 c 合約的。
  }
  function f3() public { // will set u to 1
    C.f();
  // 如果要呼叫 c 合約中的函式，需要使用函式名。
  }
}
```

需要注意的是父合約的 State Variables 不可以在子合約被更改，同時也不可以在子合約宣告在父合約們中已經宣告同樣名稱的 State Variables。
