Solidity-039 ContractPolymorphism

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.9;

// Define a contract named ParentContract

contract ParentContract {

  // Declare an internal state variable of type uint

  // Internal variables can be accessed by this contract and contracts that inherit from it

  uint internal simpleInteger;

  // Public function to set the value of simpleInteger

  // Any account can call this function to update simpleInteger's value

  function SetInteger(uint _value) public {

    simpleInteger = _value;

  }

  // Virtual public view function to return a uint value

  // Marked as virtual so it can be overridden by inheriting contracts

  // This specific implementation always returns 10, regardless of simpleInteger's value

  function GetInteger() virtual public view returns (uint) {

    return 10;

  }

}

// Define a contract named ChildContract that inherits from ParentContract

contract ChildContract is ParentContract {

  // Override the GetInteger function to return the actual value of simpleInteger

  // This allows the ChildContract to provide its own behavior for GetInteger

  function GetInteger() override public view returns (uint) {

    return simpleInteger;

  }

}

// Define a contract named Client

contract Client {

  // Instantiate a ChildContract and assign it to a variable of type ParentContract

  // Demonstrates polymorphism where a parent type variable is used to hold a child type object

  ParentContract pc = new ChildContract();

  // Public function to interact with the pc instance

  // Sets the simpleInteger value and then retrieves it using GetInteger

  // The behavior of GetInteger will be determined by the actual type of pc, which is ChildContract

  // Hence, it will return the value of simpleInteger set by SetInteger

  function WorkWithInheritance() public returns (uint) {

      pc.SetInteger(100); // Set simpleInteger to 100

      return pc.GetInteger(); // Should return 100 due to the override in ChildContract

  }

}

//Deploy:

  • 23
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值