5. Inheritance, Interfaces, and External Interaction
To build complex systems, you must know how to modularize and reuse contracts and how to communicate effectively with other contracts.
5.1. Inheritance
Solidity supports contract inheritance using the is keyword. Functionality from the parent contract is available in the child contract.
contract Parent {
address public creator;
}
contract Child is Parent {
function getCreator() public view returns (address) {
return creator;
}
}
5.2. Interfaces
Interfaces only contain function declarations, allowing external entities to know what functionality a contract provides. Only external functions can be declared.
5.3. Interacting with External Contracts
To call a function in another contract, you must instantiate it using its interface or address.
// Example: Interacting with an ERC20 token contract
interface IERC20 {
function transfer(address recipient, uint256 amount) external returns (bool);
}
contract TokenHandler {
function sendToken(address tokenAddress, address recipient, uint256 amount) public {
IERC20 token = IERC20(tokenAddress);
require(token.transfer(recipient, amount), "Token transfer failed.");
}
}
Upon mastering these five steps, you will be able to develop practical and secure Ethereum-based smart contracts.