...

/

Inheritance, Abstract Contracts, and Interfaces

Inheritance, Abstract Contracts, and Interfaces

Learn to extend the functionality of your smart contracts with code from other smart contracts, abstract contracts, and interfaces.

We'll cover the following...

Inheritance

In object-oriented programming, inheritance is a program’s ability to use another program’s functionality. In Solidity, it allows us to extend our contracts with code that has been proven to be secure and keep them organized and maintainable. The contract providing this code is known as a base contract, whereas the inheriting contract is known as a derived contract.

We declare that a contract inherits from a source using the is keyword as if to say that the derived contract is an instance of the base contract.

Press + to interact
pragma solidity >=0.4.0 <0.7.0;
contract X {}
contract Y is X {}
contract Z is Y {
// This makes Z derive from X as well
}

Code from multiple base contracts can be inherited by a single derived contract. Inheritance is also transitive—if contract Y inherits from contract X and Z inherits from Y, then contract Z will be able to use the functionality of X as well as Y, as in the example above.

Note: Only public and internal functions and state variables of a base contract are available to derived contracts; external and private visibility modifiers do not allow inheritance.

Press + to interact
pragma solidity >=0.5.0 <0.9.0;
contract sum {
function computeSum(uint num1, uint num2) internal pure returns(uint) {
return num1 + num2;
}
}
contract product {
function computeProduct(uint num1, uint num2) internal pure returns(uint) {
return num1 * num2;
}
}
contract operations is sum, product {
uint public mySum;
uint public myProduct;
function setSum(uint num1, uint num2) external returns(uint) {
mySum = computeSum(num1,num2);
return mySum;
}
function setProduct(uint num1, uint num2) external returns(uint) {
myProduct = computeProduct(num1,num2);
return myProduct;
}
}
  • Lines 2–11: We create base contracts sum and product, respectively. Each contract ...