Abstract Contracts in Solidity
In Solidity, it is possible to create abstract contracts. An abstract contract has at least one unimplemented function. Such contracts serve as a base contract from which other child contracts are derived. Derived contracts implement the empty (abstract) function and use existing implemented functions if required.
Abstract contracts can help us generalizing a contract and avoid code duplication. They facilitate patterns like the template method and improve self-documentation.
Implementation of Abstract Contracts
Abstract contracts are marked with the keyword abstract. They cannot be instantiated directly, even if they implement all defined functions.
The following code shows how to implement an abstract contract:
pragma solidity 0.8.20;
abstract contract AbstractContract{
function sum(uint256, uint256) public virtual returns(uint256);
}
contract ChildContract is AbstractContract{
function sum(uint256 _x, uint256 _y) public pure override returns(uint256 _result){
return _x + _y;
}
}
If a contract inherits from an abstract contract and doesn’t implement all not implemented functions, it has to be marked as abstract too.