继承是面向对象语言的重要特征。继承是为了模拟现实中的现象,并且可以简化代码的书写。
例如猫与够都属于动物。他们都继承动物的某些特征。
当前合约继承父类合约的属性和方法。
123456789101112131415161718192021222324252627 | contract 合约名 is 父类合约名{}``` ## 继承例子下面的例子中。直接部署son合约后,son合约继承了father合约的状态变量money与函数dahan,所以在son合约中,仍然可以访问或修改父类的状态变量和方法。同时,在son合约中,有属于自己特有的状态变量和方法。```jspragma 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的类型,可以被继承,可以在外部与内部被调用
123456789 | contract father{ uint money = 10000;}contract son is father{ function getMoney() public view returns(uint){ return money; }} |
函数默认为public属性,可以被继承,可以在外部与内部被调用
1234567891011 | contract father{ function dahan() pure returns(string){ return "dahan"; }}contract son is father{ function test() public view returns(string){ return dahan(); }} |
当为状态变量添加了inernal属性,仍然可以被继承,internal属性只能够被合约中的方法调用,不能够在外部被直接调用。
123456789 | contract father{ uint internal money = 10000;}contract son is father{ function getMoney() public view returns(uint){ return money; }} |
当为函数添加了inernal属性,仍然可以被继承,internal属性只能够被合约中的方法调用,不能够在外部被直接调用。
1234567891011 | contract father{ function dahan() internal pure returns(string){ return "dahan"; }}contract son is father{ function test() public view returns(string){ return dahan(); }} |
状态变量没有external属性,但是函数有。
当为函数加上external属性后,意味着合约只能够在外部被调用,不能够在内部被调用。
如果想合约在内部被调用,需要使用到如下this.函数
的方式:
12345678910111213 | contract father{ function dahan() external pure returns(string){ return "dahan"; }}contract son is father{ function test() public view returns(string){ return this.dahan(); }} |
能够调用external的第二种方式。
12345678910111213 | 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协议 许可协议。转载请注明出处!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。