Solidity – 多态性
多态性是一种以多种形式处理数据的能力。像任何其他编程语言一样,Solidity 也支持多态性。 Solidity 支持两种类型的多态,函数多态和合约多态。
函数多态
函数多态也称为方法重载。在函数多态中,多个函数在同一个合约或继承合约中被声明为具有相同的名称。函数因参数数量或参数数据类型而异。函数声明不能被仅返回类型不同的函数重载。
示例:在下面的示例中,合约 methodOverloading定义了两个具有相同名称但参数列表不同的函数来演示函数多态性。
Solidity
// Solidity program to demonstrate
// Function Polymorphism
pragma solidity ^0.5.0;
// Contract definition
contract methodOverloading {
// Function to get value
// of the string variable
function getValue(
string memory _strin) public pure returns(
string memory){
return _strin;
}
// function to get value of
// the unsigned integer variable
function getValue(
uint _num) public pure returns(
uint){
return _num;
}
}
Solidity
// Solidity program to demonstrate
// Contract Polymorphism
pragma solidity >=0.4.22 <0.6.0;
// Contract definition
contract parent{
// Internal state variable
uint internal sum;
// Function to set the value of
// internal state variable sum
function setValue(
uint _num1, uint _num2) public {
sum = _num1 + _num2;
}
// Function to return a value 10
function getValue(
) public view returns(uint) {
return 10;
}
}
// Defining child contract
contract child is parent{
// Function getValue overloaded
// to return internal state
// variable sum defined in the
// parent contract
function getValue(
) public view returns(uint) {
return sum;
}
}
// Defining calling contract
contract ContractPolymorphism {
// Creating object
parent pc = new child();
// Function to set values
// of 2 unsigned integers
function getInput(
uint _num1, uint _num2) public {
pc.setValue(_num1, _num2);
}
// Function to get value of
// internal state variable sum
function getSum(
) public view returns(uint){
return pc.getValue();
}
}
输出 :
契约多态性
合约多态性意味着当多个合约实例通过继承相互关联时,它们可以互换使用。这有助于使用父合约的实例调用子合约函数。
示例:在下面的示例中,合约父代是由子合约子代派生的,以展示合约多态性。 ContractPolymorphism是驱动契约。
坚固性
// Solidity program to demonstrate
// Contract Polymorphism
pragma solidity >=0.4.22 <0.6.0;
// Contract definition
contract parent{
// Internal state variable
uint internal sum;
// Function to set the value of
// internal state variable sum
function setValue(
uint _num1, uint _num2) public {
sum = _num1 + _num2;
}
// Function to return a value 10
function getValue(
) public view returns(uint) {
return 10;
}
}
// Defining child contract
contract child is parent{
// Function getValue overloaded
// to return internal state
// variable sum defined in the
// parent contract
function getValue(
) public view returns(uint) {
return sum;
}
}
// Defining calling contract
contract ContractPolymorphism {
// Creating object
parent pc = new child();
// Function to set values
// of 2 unsigned integers
function getInput(
uint _num1, uint _num2) public {
pc.setValue(_num1, _num2);
}
// Function to get value of
// internal state variable sum
function getSum(
) public view returns(uint){
return pc.getValue();
}
}
输出 :