Inheritance and Interfaces
Utilize inheritance for code reusability and define clear contract APIs using interfaces for better modularity.
What is Inheritance?
In Solidity, inheritance allows one smart contract (the child) to reuse code, functions, and state variables from another contract (the parent). This is a fundamental concept in object-oriented programming.
- It promotes code reusability.
- It helps organize complex contract logic.
- It allows for modular and extensible designs.
Basic Inheritance Syntax
To make a contract inherit from another, you use the is keyword. The child contract gets access to all public and internal members of the parent contract.
Think of it like a child inheriting traits from its parent.
pragma solidity ^0.8.0;
contract ParentContract {
uint public parentValue;
constructor() {
parentValue = 100;
}
function getParentValue() public view returns (uint) {
return parentValue;
}
}
contract ChildContract is ParentContract {
// ChildContract inherits parentValue and getParentValue()
}