1. 程式人生 > >solidity智慧合約[34]-合約繼承與可見性

solidity智慧合約[34]-合約繼承與可見性

繼承

繼承是面嚮物件語言的重要特徵。繼承是為了模擬現實中的現象,並且可以簡化程式碼的書寫。
例如貓與夠都屬於動物。他們都繼承動物的某些特徵。

繼承語法

當前合約繼承父類合約的屬性和方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
contract  合約名  is  父類合約名{

}
```                              


## 繼承例子

下面的例子中。直接部署son合約後,son合約繼承了father合約的狀態變數money與函式dahan,所以在son合約中,仍然可以訪問或修改父類的狀態變數和方法。
同時,在son合約中,有屬於自己特有的狀態變數和方法。
```js
pragma solidity ^0.4.23;


contract father{
   uint public money  =10000;
   function dahan() public returns(string){
       return "dahan";
   }

}

contract son is father{
   uint public girlfriend;
   //修改父類屬性
   function change() public{
       money = 99;
   }
}

繼承與可見性

public

狀態變數預設是public的型別,可以被繼承,可以在外部與內部被呼叫

1
2
3
4
5
6
7
8
9
contract father{
   uint  money  = 10000;

}

contract son is father{
   function getMoney() public view returns(uint){
      return money;
   }
}

函式預設為public屬性,可以被繼承,可以在外部與內部被呼叫

1
2
3
4
5
6
7
8
9
10
11
contract father{
 function dahan()  pure returns(string){
      return "dahan";
  }
}

contract son is father{
 function test() public view returns(string){
     return dahan();
 }
}

internal

當為狀態變數添加了inernal屬性,仍然可以被繼承,internal屬性只能夠被合約中的方法呼叫,不能夠在外部被直接呼叫。

1
2
3
4
5
6
7
8
9
contract father{
   uint internal money  = 10000;
}

contract son is father{
   function getMoney() public view returns(uint){
      return money;
   }
}

當為函式添加了inernal屬性,仍然可以被繼承,internal屬性只能夠被合約中的方法呼叫,不能夠在外部被直接呼叫。

1
2
3
4
5
6
7
8
9
10
11
contract father{
 function dahan() internal pure returns(string){
      return "dahan";
  }
}

contract son is father{
 function test() public view returns(string){
     return dahan();
 }
}

external

狀態變數沒有external屬性,但是函式有。
當為函式加上external屬性後,意味著合約只能夠在外部被呼叫,不能夠在內部被呼叫。
如果想合約在內部被呼叫,需要使用到如下this.函式的方式:

1
2
3
4
5
6
7
8
9
10
11
12
13
contract father{

   function dahan() external pure returns(string){
       return "dahan";
   }
}

contract son is father{    
   function test() public view returns(string){
       return this.dahan();
   }

}

能夠呼叫external的第二種方式。

1
2
3
4
5
6
7
8
9
10
11
12
13
contract father{

   function dahan() external pure returns(string){
       return "dahan";
   }
}
contract testExternal{
  father f = new father();

    function test() public view returns(string){
       return f.dahan();
   }
}

image.png