Hierarchical Inheritance
Example
pragma solidity ^0.8.0;
// Base contract
contract Animal {
string public animalType;
constructor(string memory _animalType) {
animalType = _animalType;
}
function speak() public virtual returns (string memory);
}
// Child contract that inherits from the Animal contract
contract Cat is Animal {
constructor() Animal("Cat") {}
function speak() public override returns (string memory) {
return "Meow";
}
}
// Another child contract that inherits from the Animal contract
contract Dog is Animal {
constructor() Animal("Dog") {}
function speak() public override returns (string memory) {
return "Woof";
}
}
// Child contract that inherits from both the Cat and Dog contracts
contract CatDog is Cat, Dog {
constructor() Cat() Dog() {}
// Override speak function from Animal contract
function speak() public override(Cat, Dog) returns (string memory) {
string memory catSpeak = Cat.speak();
string memory dogSpeak = Dog.speak();
return string(abi.encodePacked(catSpeak, " ", dogSpeak));
}
}Last updated