Inheritance in Solidity smart contracts

With Solidity contracts one can use inheritance which is a way of extending the functionality of a contract, helps organize code, and increases the re-usability.

Solidity supports inheritance between smart contracts, where multiple contracts can be inherited into a single contract. 

The sample contract below demonstrate the use of inheritance. MyFirstContract inherits from Bank

//contract 2 will inherit contract 1
pragma solidity ^0.5.0;

interface Regulator {
    function checkValue (uint amount) external returns (bool);
    function loan() external returns (bool);
    }

//the bank contract is using the regulator interface
contract Bank is Regulator {
    uint private value;
    address private owner;
    
    }
    
    constructor(uint amount) public {
        value = amount;
        owner = msg.sender;
    }
    
    function deposit(uint amount) public {
        value += amount;
    }
    
    function withdraw(uint amount) public {
        if (checkValue(amount)) {
            value -= amount;
        }
    }
    
    function balance() public view returns (uint) {
        return value;
    }
    
    function checkValue(uint amount) public returns (bool){
        return amount >= value;
    }
    
    function loan() public returns (bool) {
        return value > 0;
    }
    
}

//myfirstcontract is inheriting the bank contract
//it is putting 10 as the amount for the constructor
contract MyFirstContract is Bank (10) {
    string private name;
    uint private age;
    
    function setName(string memory newName) public {
        name = newName;
    }
    
    function getName () public view returns (string memory) {
        return name;
    }
    
    function setAge(uint newAge) public {
        age = newAge;
        
    }
    
    function getAge () public view returns (uint) {
        return age;
    }
    
    
}

Try it in Remix

For more information read the docs.

This code is for learning and entertainment purposes only. The code has not been audited and use at your own risk. Remember smart contracts are experimental and could contain bugs.

Click here for more information about how to use the Ethereum test network and how to obtain test ETH.

Next Review – Create an If Statement in a Solidity smart contract

-->

Leave a Reply