Like any oops language, Solidity provides Interfaces in contracts. Contract interfaces are similar to Interfaces i in OOS language such as Java and typescript.
Solidity Interface
Interface
is an abstract design of an contract and similar to Abstract Contract
in Solidity.
It created using interface
keyword,Contains function declaration without body.
Interface functions always ends with semicolon
.
Syntax of interface
interface name{
function name() returns (string)
}
``
Notes:
- Interface contracts only contains function declaration or header, No implementation in function.
- It does not contain a constructor
- It is not possible to use local or state Variables in interface
- Interfaces can not be extend by other contracts or interfaces
- Functions defined in Abstract without implementation created with virtual keyword
- It is not possible with creating an instance of an Interface contracts
- Function header in interface always end with semicolon.
Here is an example to declare an interface
```markup
pragma solidity >=0.4.0 <0.7.0;
interface Animal {
function eat() public virtual returns (bytes32);
}
Once Interface contract declared, You need to extend by using is
keyword
Syntax
contract DerivedContract is InterfaceContract
Here is an exmaple
pragma solidity >=0.4.0 <0.7.0;
contract Lion is Animal {
function eat() public view returns(
string memory){
return _strIn;
}(bytes32){
}
}
Following Invalid interfaces in Solidity,
And the following code snippens gives an compilation error
- No function implementation
pragma solidity >=0.4.0 <0.7.0;
interface Animal {
// function body is not allowed
function eat() public virtual returns (bytes32){
}
}
- variables in interfaces are not allowed
pragma solidity >=0.4.0 <0.7.0;
interface Animal {
uint age; // not valid
constructor(){
}
function eat() public virtual returns (bytes32); }
}
- Constructor in interfaces are not allowed
pragma solidity >=0.4.0 <0.7.0;
interface Animal {
// constructor not allowed
constructor(){
}
function eat() public virtual returns (bytes32); }
}