0
0
Blockchain / Solidityprogramming~5 mins

Why inheritance promotes code reuse in Blockchain / Solidity

Choose your learning style9 modes available
Introduction

Inheritance lets you build new code using existing code. This saves time and avoids repeating the same work.

When you want to create a new smart contract that shares features with an existing one.
When you want to add new abilities to a contract without rewriting old code.
When you want to fix or improve common code in one place and have all related contracts use the update.
When you want to organize your contracts in a clear, logical way by grouping shared code.
When you want to save gas by reusing tested and optimized code instead of copying it.
Syntax
Blockchain / Solidity
contract Parent {
    // common code here
}

contract Child is Parent {
    // new or extended code here
}

The is keyword shows inheritance from the parent contract.

Child contracts get all functions and variables from the parent automatically.

Examples
Dog inherits from Animal and changes the sound function.
Blockchain / Solidity
contract Animal {
    function sound() public pure returns (string memory) {
        return "Some sound";
    }
}

contract Dog is Animal {
    function sound() public pure override returns (string memory) {
        return "Bark";
    }
}
MyContract inherits the owner variable and constructor from Ownable.
Blockchain / Solidity
contract Ownable {
    address owner;
    constructor() {
        owner = msg.sender;
    }
}

contract MyContract is Ownable {
    // MyContract can use owner variable
}
Sample Program

The Car contract inherits the move function from Vehicle. The Test contract creates a Car and calls both move and honk.

Blockchain / Solidity
pragma solidity ^0.8.0;

contract Vehicle {
    function move() public pure returns (string memory) {
        return "Moving";
    }
}

contract Car is Vehicle {
    function honk() public pure returns (string memory) {
        return "Beep beep!";
    }
}

contract Test {
    function testCar() public pure returns (string memory, string memory) {
        Car myCar = new Car();
        return (myCar.move(), myCar.honk());
    }
}
OutputSuccess
Important Notes

Inheritance helps keep your code clean and easy to update.

Be careful with multiple inheritance to avoid conflicts.

Summary

Inheritance lets new contracts reuse code from existing ones.

This saves time and reduces mistakes by avoiding repeated code.

It helps organize contracts and makes updates easier.