In this article we will be having a look at solidity polymorphism techniques which will help us to use the solidity functions in an efficient way.
Solidity, just like any other programming language, has the capacity for processing data in multiple forms, which is known as polymorphism.
In particular, Solidity enables two kinds of polymorphism:
- Function Polymorphism.
- Contract Polymorphism.
Firstly, we will be learning about function polymorphism.
Solidity Polymorphism – Function
Method overloading, or Function Polymorphism, is a feature that enables declaring several functions with the same name within a contract or an inherited contract.
Two functions having the same name can be overloaded by changing the number of parameters or the data type of the parameters.
The following example shows the get_Sum() function being overloaded, by changing the data types of its parameters:
Above example is a Solidity smart contract that demonstrates function polymorphism, specifically method overloading.
The contract is called “SolidityTest” and defines two functions with the same name, “get_Sum“, but with different input parameter types (uint and int).
The first function takes two unsigned integers (uint mrx and uint ample) as inputs, and returns their sum as an unsigned integer (uint).
The second function takes two signed integers (int mrx and int ample) as inputs, and returns their sum as a signed integer (int).
This means that if a user calls the “get_Sum” function with two uint inputs, the first function will be executed and return a uint result.
On the other hand, if a user calls the same function with two int inputs, the second function will be executed and return an int result.
Correspondingly, the same process of function overloading can be done by changing the number of parameters of the function as shown below:
Lets move on to the second type of solidity polymorphism which is contract polymorphism.
It refers to the practice of utilizing multiple instances of related contracts interchangeably by means of inheritance.
This allows for child contract functions to be called using a parent contract instance.
The following example will help us to understand the contract polymorphism: