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();
}
}
本文链接:https://dreamerjonson.com/2018/11/22/solidity-34-inherit/
版权声明:本博客所有文章除特别声明外,均采用CC BY 4.0 CN协议许可协议。转载请注明出处!
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。