0
0
Blockchain / Solidityprogramming~5 mins

Abstract contracts in Blockchain / Solidity

Choose your learning style9 modes available
Introduction

Abstract contracts help you create a base template for other contracts. They define functions without full details, so others can build on them.

When you want to define common rules for many contracts without writing full code each time.
When you want to force other contracts to implement certain functions.
When you want to organize your code better by separating shared logic from specific details.
Syntax
Blockchain / Solidity
abstract contract ContractName {
    // Declare functions without implementation
    function functionName() public virtual;

    // You can also have implemented functions
    function implementedFunction() public {
        // code here
    }
}

An abstract contract cannot be deployed directly.

Functions without implementation must be declared without a body and marked as virtual.

Examples
This abstract contract defines a function startEngine without details. Other contracts must provide the details.
Blockchain / Solidity
abstract contract Vehicle {
    function startEngine() public virtual;
}
Here, area is abstract and must be implemented. description has code and can be used as is.
Blockchain / Solidity
abstract contract Shape {
    function area() public virtual returns (uint);
    function description() public {
        // This function has implementation
    }
}
Sample Program

This program shows an abstract contract Animal with an abstract function sound. The Dog contract implements this function. The Test contract creates a Dog and gets its sound.

Blockchain / Solidity
pragma solidity ^0.8.0;

abstract contract Animal {
    // Abstract function without implementation
    function sound() public virtual returns (string memory);
}

contract Dog is Animal {
    // Implementing the abstract function
    function sound() public override returns (string memory) {
        return "Woof!";
    }
}

contract Test {
    function getDogSound() public returns (string memory) {
        Dog dog = new Dog();
        return dog.sound();
    }
}
OutputSuccess
Important Notes

Time complexity depends on the functions implemented in child contracts, not the abstract contract itself.

Abstract contracts save space by avoiding repeated code and enforce rules for child contracts.

Common mistake: Trying to deploy an abstract contract directly will cause an error.

Use abstract contracts when you want to force other contracts to implement certain functions, unlike interfaces which only declare functions without any code.

Summary

Abstract contracts define functions without full code to be completed by child contracts.

They cannot be deployed alone but help organize and enforce rules.

Child contracts must implement all abstract functions.