In this tutorial, we will explore the syntax for contracts, contract inheritance, abstract contracts, interfaces, events, and libraries in Solidity.

Contracts

In Solidity, a contract is a collection of functions and data (state variables) that resides at a specific address on the Ethereum blockchain. A contract can interact with other contracts, receive Ether, and send Ether to other contracts.

Creating Contracts Using new

To create a contract from another contract, you can use the new keyword. The source of the contract has to be known in advance. Here's an example:

contract A {
    function add(uint _a, uint _b) returns (uint) {
        return _a + _b;
    }
}

contract C {
    address a;

    function f(uint _a) {
        a = new A();
    }
}

Contract Inheritance

Solidity supports multiple inheritance and polymorphism. Inheritance allows you to create new contracts based on existing contracts, inheriting their functions and state variables.

contract owned {
    function owned() { owner = msg.sender; }
    address owner;
}

contract mortal is owned {
    function kill() {
        if (msg.sender == owner) selfdestruct(owner);
    }
}

contract final is mortal {
    function kill() {
        super.kill(); // Calls kill() of mortal.
    }
}

Multiple Inheritance

You can inherit from multiple contracts in Solidity:

contract A {}
contract B {}
contract C is A, B {}

Constructor of Base Class

If a base class has a constructor, you need to call it explicitly in the derived contract:

contract A {
    uint a;
    constructor(uint _a) { a = _a; }
}

contract B is A(1) {
    constructor(uint _b) A(_b) {
    }
}

Abstract Contracts

An abstract contract is a contract that contains implemented and non-implemented functions. Such contracts cannot be compiled, but they can be used as base contracts.

pragma solidity ^0.4.0;

contract A {
    function C() returns (bytes32);
}

contract B is A {
    function C() returns (bytes32) { return "c"; }
}

Interface

An interface is similar to an abstract contract, but it has restrictions. Interfaces cannot have any functions implemented, inherit other contracts or interfaces, define constructors, variables, structs, or enums.