Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 47 ยท Object-Oriented Solidity

Encapsulation, Polymorphism and Inheritance Shapes

Hide state behind validated functions, overload and override functions, call different contracts through one interface, and use multi-level and hierarchical inheritance.

Solidity is not a classic object-oriented language, but contracts behave a lot like classes: they hold state, expose functions, extend other contracts and can be used through shared interfaces. Four ideas from object-oriented design carry over directly: encapsulation (hide the data, expose safe operations), inheritance (reuse and extend), and polymorphism (one name or one interface, several behaviors).

Inheritance and Overriding explained the mechanics of is, virtual, override and linearization. This lesson uses those mechanics to show the design patterns that grow from them: how to protect state, the common inheritance shapes (single, multi-level, hierarchical), and the two kinds of polymorphism you will meet in real code, function overloading and contract polymorphism through interfaces and overrides.

Encapsulation

Encapsulation means the data of a contract is only changed through functions that enforce the rules. Instead of letting anyone set a balance, you expose deposit and withdraw, which check conditions. Solidity gives you visibility keywords for this.

Keyword Who can use it
private Only code inside the same contract
internal The contract and contracts that inherit from it (the default for state variables)
public Everyone; for a state variable the compiler also generates a getter
external Only from outside (other contracts and transactions), functions only
SOLIDITY
contract Account {
    address private _owner;          // hidden from other contracts
    uint256 private _balance;

    constructor() {
        _owner = msg.sender;
    }

    function balance() external view returns (uint256) {   // a read-only "getter"
        return _balance;
    }

    function deposit() external payable {
        _balance += msg.value;
    }

    function withdraw(uint256 amount) external {
        require(msg.sender == _owner, "not owner");
        require(amount <= _balance, "insufficient funds");
        _balance -= amount;
        payable(msg.sender).transfer(amount);
    }
}

The only way to change _balance is through deposit and withdraw. Outside code cannot assign account._balance = 1_000_000.

private is not secret. Visibility controls which code may access a variable. It does not hide the data: all contract storage is public on the blockchain and anyone can read it with eth_getStorageAt. Never keep a password or a secret random seed in a private variable. See Storage, Memory and Calldata.

Good encapsulation habits: make state private or internal by default, expose reads through view functions, put validation into the single function that writes a value (a setter), and use modifiers for access checks. A public state variable is fine when anyone may read it and only your own functions write it, because the generated getter is read-only.

Inheritance shapes

A contract inherits with is. Beyond plain single inheritance, three shapes appear all the time.

Multi-level inheritance is a chain: C is B and B is A. C gets everything from both ancestors.

SOLIDITY
contract Animal {
    function breathe() public pure returns (string memory) { return "breathing"; }
}

contract Mammal is Animal {
    function feed() public pure returns (string memory) { return "milk"; }
}

contract Dog is Mammal {
    function speak() public pure returns (string memory) { return "woof"; }
}
// A deployed Dog has breathe(), feed() and speak().

Hierarchical inheritance is one parent with several children. Each child gets the parent's code but is independent of its siblings.

SOLIDITY
contract Shape {
    function sides() public view virtual returns (uint256) { return 0; }
}

contract Triangle is Shape {
    function sides() public pure override returns (uint256) { return 3; }
}

contract Square is Shape {
    function sides() public pure override returns (uint256) { return 4; }
}

Multiple inheritance lists several parents (contract D is B, C) and was covered with linearization in Inheritance and Overriding. List parents "from most base-like to most derived". When one contract extends another, Solidity actually copies the parent's code into the child's bytecode; there is only one deployed contract, not a parent and child that talk to each other.

Polymorphism: function overloading

Overloading means several functions in one contract share a name but differ in the number or types of their parameters. The compiler picks the right one from the arguments at the call site.

SOLIDITY
contract Printer {
    function show(uint256 n) public pure returns (string memory) { return "number"; }
    function show(string memory s) public pure returns (string memory) { return "text"; }
    function show(uint256 a, uint256 b) public pure returns (string memory) { return "pair"; }
}

Rules and traps:

  • The return type is not part of the signature, so two functions that differ only in the return type are an error.
  • Resolution happens at compile time with implicit conversions. Calling show(5) with a plain literal could match both uint8 and uint256 overloads, which causes an "ambiguous" compile error. Make the type explicit: show(uint8(5)).
  • In the ABI, each overload has its own signature (show(uint256), show(string), show(uint256,uint256)), and therefore its own four-byte selector. A client library that finds functions by name has to be told which one you mean. With ethers you write contract["show(uint256)"](5).
  • Overloading is common in libraries (safeTransferFrom with and without a data argument in ERC-721 is a classic example), but too many overloads make code hard to read. When two overloads do quite different things, give them different names.

Polymorphism: overriding and interfaces

The second kind is contract polymorphism: code written against a general type works with many concrete implementations, and the specific behavior is chosen when it runs. In Solidity this is done with virtual and override, or with interfaces.

Here a function takes an address that points to any contract implementing IShape:

SOLIDITY
interface IShape {
    function area() external view returns (uint256);
}

contract Rectangle is IShape {
    uint256 public w; uint256 public h;
    constructor(uint256 _w, uint256 _h) { w = _w; h = _h; }
    function area() external view override returns (uint256) { return w * h; }
}

contract Circle is IShape {
    uint256 public r;
    constructor(uint256 _r) { r = _r; }
    function area() external view override returns (uint256) { return 3 * r * r; }  // rough pi
}

contract AreaSum {
    function total(IShape[] calldata shapes) external view returns (uint256 sum) {
        for (uint256 i = 0; i < shapes.length; i++) {
            sum += shapes[i].area();   // which area()? decided by each contract
        }
    }
}

AreaSum does not know about Rectangle or Circle. It only knows the IShape interface, so you can add a Triangle later and AreaSum works unchanged. The same idea is how tokens work: wallets and exchanges call the ERC-20 interface on thousands of different token contracts. Inside a single inheritance tree, a call through a base type picks the most derived override (virtual functions dispatch by the actual contract), and super calls the next version up the chain.

Try it: inheritance shapes and overriding

JavaScript classes can model the same structure. The program below builds a multi-level chain, a hierarchical family and the "most derived wins" rule, and prints which version each call reaches.

JS Multi-level and hierarchical inheritance

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Try it: overloading and interface polymorphism

Solidity picks an overload by the argument types; the stand-in below computes a signature from the arguments and looks it up, which is what the ABI does. Then it shows AreaSum working with shapes it has never seen.

JS Overloads by signature and a shared interface

Press Run (or Ctrl + Enter) to see the console output here.

No output.

What is real: visibility rules, the shapes of inheritance, overload resolution by parameter types (with the ABI signature as the identity), and calling contracts through an interface are all how Solidity works. What is the stand-in: JavaScript classes use prototypes rather than copying bytecode, and the signature lookup is a tiny model of what the compiler and the ABI do.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Does marking a state variable private hide its value from people reading the blockchain?

    All contract storage can be read from a node. private limits access from other contracts' code, it does not encrypt anything.
  2. 2. Which is an example of hierarchical inheritance?

    Hierarchical inheritance has one parent with several children. A chain of parents is multi-level, and listing several parents in one contract is multiple inheritance.
  3. 3. Two functions have the same name and parameters but different return types. What happens?

    An overload must differ in its parameters. The return type is not part of the function signature.
  4. 4. Why can AreaSum work with a Triangle contract written after it was deployed?

    AreaSum depends only on the interface function area(). Any contract that implements it can be passed in, which is polymorphism.
  5. 5. What is the ABI signature of function show(uint256 a, string memory s)?

    The signature is the name plus the canonical parameter types without names or data locations. The selector is the first four bytes of its keccak256 hash.

Summary

  • Encapsulation: keep state private or internal, write it only through functions that validate, and expose reads through view functions. private limits code access but does not hide data.
  • Inheritance shapes: multi-level (a chain), hierarchical (one parent, many children) and multiple (several parents, linearized). The parent's code is merged into the child's bytecode.
  • Overloading gives one name several parameter lists; the ABI treats each as a separate signature and selector. Beware ambiguous literals.
  • Contract polymorphism means code that depends on an interface or a base contract works with any implementation, and overrides decide the behavior.

Next: how contracts take and send raw bytes, in ABI Encoding and Low-Level Calls.