We have explored a number of topics, and when writing smart contracts we find that we often use the same pattern: for example, smart contracts have owners that are set in constructors and then generate modifiers so that only the owner can use some of the functionality. What if we create a base contract to implement these features and reuse them in future smart contracts? As you can guess, we’re going to use inheritance.

In Solidity, inheritance is very similar to classic object-oriented programming languages. You write the basic smart contract first and inform yourself that your new smart contract will inherit from the base contract.

You must also get an idea of Solidity support for multiple inheritance by copying code that contains polymorphism. All function calls are virtual, meaning the function that calls the most derived functions, unless the contract name is explicitly given. When a single smart contract inherits from multiple contracts, only one smart contract is created on the blockchain, and all the code from the underlying contract is copied into the created smart contract.

Let’s write down our basic smart contract: it will let us easily add ownership to our contract. We’ll call it Ownable. The people at OpenZeppelin wrote a lot of reusable code that could be used in smart contracts. These snippets are available through its tools or its Github repository.

Here’s the code:

Pragma solidity ^ 0.4.11; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control *functions, this simplifies the implementation of "user permissions".
 */
contract Ownable {

  address public owner;

  /**
   * @dev The Ownable constructor sets the original `owner` of the contract to the sender
   * account.
   */
  function Ownable() {
    owner = msg.sender;
  }


  /**
   * @dev Throws if called by any account other than the owner.
   */
  modifier onlyOwner() {
    require(msg.sender == owner);
    _;
  }


  /**
   * @dev Allows the current owner to transfer control of the contract to a newOwner.
   * @param newOwner The address to transfer ownership to.
   */
  function transferOwnership(address newOwner) onlyOwner {
    require(newOwner != address(0));      
    owner = newOwner;
  }

}
Copy the code

Another pattern we often write about is the ability to break our contract and transfer the money stored in the contract to the owner or another address. The important thing is that we don’t want anyone to be able to break our contract, so our Destructible should inherit Ownable. Inheritance is done using the IS keyword after the smart contract name.

It must be noted that it is Solidity, a function by default, or can be accessed from derived classes. As with other programming languages, you can specify what is accessible from an external or derived contract. Functions can be specified as external, public, internal, private, and public by default.

  • externalExternal functions are part of the smart contract interface, which means they can be called from other contracts and transactions.externalFunction f cannot be called internally (that is, f() does not work, but this.f() does). External functions can sometimes be more efficient when they receive large amounts of data.
  • public: Public functions are part of the smart contract interface and can be called internally or through messages. For public state variables, automatic getters are generated (see below).
  • internal: These functions and state variables can only be accessed internally (that is, from or derived from the current contract) and are not otherwise used.
  • private: Private functions and state variables are visible only to the smart contract that defines them, not to the derived contract.

Here is our second smart contract:

Pragma solidity ^ 0.4.11; /** * @title Destructible * @dev Base contract that can be destroyed by owner. All fundsin contract will be sent to the owner.
 */
contract Destructible is Ownable {

  function Destructible() payable { } 

  /**
   * @dev Transfers the current balance to the owner and terminates the contract. 
   */
  function destroy() onlyOwner {
    selfdestruct(owner);
  }

  functiondestroyAndSend(address _recipient) onlyOwner { selfdestruct(_recipient); }}Copy the code

Now using these two basic contracts, we will write a simple BankAccount smart contract that people can remit and owners can withdraw.

Pragma solidity ^ 0.4.11; contract BankAccount is Ownable, Destructible {function store() public payable {
      
  } 

  function withdraw(uint amount) public onlyOwner {
      if(this.balance >= amount) { msg.sender.transfer(amount); }}}Copy the code

Note that we need to inherit from two smart contracts. The order of inheritance is important. A simple rule for determining order is to specify base classes from “most similar to base classes” to “most derived.”

Here is the entire code we will deploy:

Pragma solidity ^ 0.4.11; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control *functions, this simplifies the implementation of "user permissions".
 */
contract Ownable {

  address public owner;

  /**
   * @dev The Ownable constructor sets the original `owner` of the contract to the sender
   * account.
   */
  function Ownable() {
    owner = msg.sender;
  }


  /**
   * @dev Throws if called by any account other than the owner.
   */
  modifier onlyOwner() {
    require(msg.sender == owner);
    _;
  }


  /**
   * @dev Allows the current owner to transfer control of the contract to a newOwner.
   * @param newOwner The address to transfer ownership to.
   */
  functiontransferOwnership(address newOwner) onlyOwner { require(newOwner ! = address(0)); owner = newOwner; } } /** * @title Destructible * @dev Base contract that can be destroyed by owner. All fundsin contract will be sent to the owner.
 */
contract Destructible is Ownable {

  function Destructible() payable { } 

  /**
   * @dev Transfers the current balance to the owner and terminates the contract. 
   */
  function destroy() onlyOwner {
    selfdestruct(owner);
  }

  function destroyAndSend(address _recipient) onlyOwner {
    selfdestruct(_recipient);
  }
}

contract BankAccount is Ownable, Destructible {

  function store() public payable {
      
  } 

  function withdraw(uint amount) public onlyOwner {
      if(this.balance >= amount) { msg.sender.transfer(amount); }}}Copy the code

We can now deploy our bank Account smart contract.

After deployment, we can see that we see our bank account functionality, but we also see inheritance functionality.

= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =

Share some interactive online programming tutorials related to blockchain such as Ethereum, EOS and Bitcoin:

  • Java Ethereum development tutorial, mainly for Java and Android programmers for blockchain Ethereum development web3J details.
  • Python Ethereum is a detailed explanation of blockchain ethereum development by Python engineers using Web3.py.
  • PHP Ethereum, mainly introduces the use of PHP for smart contract development interaction, account creation, transactions, transfers, token development, filters and transactions and other content.
  • Ethereum introductory course, mainly introduces smart contract and DAPP application development, suitable for entry.
  • Ethereum development advanced tutorial, mainly introduces the use of Node.js, mongodb, blockchain, IPFS to achieve decentralized e-commerce DApp combat, suitable for advanced.
  • C# ethereum, mainly explains how to use C# based development. Net ethereum applications, including account management, status and transactions, smart contract development and interaction, filters and transactions, etc.
  • This course will help you get a quick start on the development of EOS blockchain decentralized applications. It covers core knowledge points such as EOS tool chain, account and wallet, issuing tokens, development and deployment of smart contracts, and interaction between codes and smart contracts. Finally, the development of a notepad DApp will be completed using all knowledge points comprehensively.
  • Java development tutorial COINS, this course for beginners, content covers the core concepts of COINS, such as block mechanism, key chain store, decentralized consensus and script, trading and UTXO etc, also explained how to integrate the currency support functions in Java code, such as creating address wallet, tectonic naked trading, management, Is a rare bitcoin development course for Java engineers.
  • PHP currency development tutorial, this course for beginners, content covers the core concepts of COINS, such as block mechanism, key chain store, decentralized consensus and script, trading and UTXO etc, also explained how to integrated the currency support functions in PHP code, such as creating address wallet, tectonic naked trading, management, This is a rare bitcoin development course for Php engineers.
  • Tendermint blockchain development in detail, this course is suitable for engineers who want to use Tendermint blockchain development, the course content includes the core concepts of tendermint application development model, such as ABCI interface, Merkle tree, multi-version state library, etc., also includes the rich practical code such as token issuance. It is the best choice for go language engineers to quickly start blockchain development.

Huizhi net original translation, reprint please indicate the source. Here is inheritance in the original Solidity language development