Inheritance, abstract, and interface

Many of the most widely used programming languages (such as C++, Java, Go, and Python, and so on) support object-oriented programming (OOP) and support inheritance, encapsulation, abstraction, and polymorphism. Inheritance enables code reuse and extensibility. Solidity supports multiple inheritance in the form of copying code, which includes polymorphism. Even if a contract inherits from multiple other contracts, only a single contract is created on the blockchain.

In solidity, inheritance is pretty similar to classic oriented-object programming languages. Here are a number of examples, as follows:

pragma solidity ^0.4.24;
contract Animal {
constructor() public {
}
function name() public returns (string) {
return "Animal";
}
function color() public returns (string);
}
contract Mammal is Animal {
int size;
constructor() public {
}
function name() public returns (string) {
return "Mammal";
}
function run() public pure returns (int) {
return 10;
}
function color() public returns (string);
}
contract Dog is Mammal {
function name() public returns (string) {
return "Dog";
}
function color() public returns (string) {
return "black";
}
}

Dog inherits from Mammal, whose parent contract is Animal. When calling Dog.run(), it will call its parent method run() and return ten. When calling name, Dog.name() will override its patent method and return the output from Dog.

In solidity, a method without a body (no implementation) is known as an abstract method. A contract that contains an abstract method cannot be instantiated, but can be used as a base.

If a contract inherits from an abstract contract, then the contract must implement all the abstract methods of abstract parent class, or it has to be declared abstract as well.

Dog has a concrete color() method, which is a concrete contract and can be compiled, but the parent contract—mammal, and the grandparent contract—animal, are still abstract contracts.

Interfaces in solidity are similar to abstract contracts; they are implicitly abstract and cannot have implementations. An abstract contract can have instance methods that implement a default behavior. There are more restrictions in interfaces, as follows:

  • Cannot inherit other contracts or interfaces
  • Cannot define constructor
  • Cannot define variables
  • Cannot define structs
  • Cannot define enums
pragma solidity ^0.4.24;
//interface
contract A {
function doSomething() public returns (string);
}
//contract implements interface A
contract B is A {
function doSomething() public returns (string) {
return "Hello";
}
}

In the preceding example, the contract is an interface, contract B implements interface A, and has a concrete doSomething() method.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.15.38.176