OOPs in Solidity

ASHDEEP SINGH - Jul 28 - - Dev Community

Contract and Objects

In Solidity, a contract is a fundamental building block of Ethereum applications. It is analogous to a class in object-oriented programming and can include state variables, functions, function modifiers, events, and struct types.

Example:

pragma solidity ^0.8.0;

contract SimpleContract {
    uint public data;

    function setData(uint _data) public {
        data = _data;
    }

    function getData() public view returns (uint) {
        return data;
    }
}
Enter fullscreen mode Exit fullscreen mode

Inheritance

Inheritance in Solidity allows a contract to inherit properties and functions from another contract. This enables code reuse and the creation of complex systems.

Example:

pragma solidity ^0.8.0;

contract BaseContract {
    uint public data;

    function setData(uint _data) public {
        data = _data;
    }
}

contract DerivedContract is BaseContract {
    function incrementData() public {
        data += 1;
    }
}
Enter fullscreen mode Exit fullscreen mode

Abstract Class

An abstract contract is a contract that contains at least one function without an implementation. It cannot be instantiated directly and must be inherited by another contract that implements the missing functions.

Example:

pragma solidity ^0.8.0;

abstract contract AbstractContract {
    function getData() public view virtual returns (uint);
}

contract ConcreteContract is AbstractContract {
    uint public data;

    function getData() public view override returns (uint) {
        return data;
    }

    function setData(uint _data) public {
        data = _data;
    }
}
Enter fullscreen mode Exit fullscreen mode

Interface

An interface in Solidity is a contract that only contains the signatures of functions, without any implementation. Interfaces are used to define the contract's external functionality, which must be implemented by another contract.

Example:


pragma solidity ^0.8.0;

interface IContract {
    function getData() external view returns (uint);
    function setData(uint _data) external;
}

contract ImplementContract is IContract {
    uint public data;

    function getData() external view override returns (uint) {
        return data;
    }

    function setData(uint _data) external override {
        data = _data;
    }
}
Enter fullscreen mode Exit fullscreen mode

Summary

Contract and Objects: Solidity contracts are like classes and can include state variables, functions, and more.
Inheritance: Allows a contract to inherit properties and functions from another contract for code reuse.
Abstract Class: A contract with at least one unimplemented function that must be inherited and implemented by another contract.
Interface: A contract with only function signatures and no implementation, used to define a contract's external functionality.

. . . . . . . . . . . . .
Terabox Video Player