Inheritance

Inheritance in Solidity is the ability for a contract to inherit properties and methods from a parent contract. In Solidity, inheritance can be achieved using the is keyword.

The child contract (the derived contract) inherits all the properties and methods of the parent contract (the base contract). The child contract can also have additional properties and methods that are unique to it.

Example

contract Animal {
    string public species;

    constructor(string memory _species) {
        species = _species;
    }

    function speak() public view returns (string memory) {
        return "Animal speaks";
    }
}

contract Dog is Animal {
    constructor() Animal("Dog") {}

    function speak() public view returns (string memory) {
        return "Bark";
    }
}

In this example, the Dog contract is inheriting from the Animal contract using the is keyword. The Dog contract has access to all the properties and methods of the Animal contract, including the species property and the speak() method. The Dog contract also has a speak() method that overrides the speak() method in the Animal contract.

Last updated