Like any oops language, Solidity provides Interfaces in contracts. Contract interfaces are similar to Interfaces in OOS languages such as Java and typescript.
Solidity Interface
Interface
is an abstract design of a contract and is similar to an Abstract Contract
in Solidity.
It was created using the interface
keyword, which Contains a function declaration without a body.
Interface functions always end with a semicolon
.
Syntax of interface
interface name{
function name() returns (string)
}
``
Notes:
- Interface contracts only contain 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 the interface
- Interfaces can not be extended 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
- The function header in the interface always ends with a semicolon.
Here is an example to declare an interface
```bash
pragma solidity >=0.4.0 <0.7.0;
interface Animal {
function eat() public virtual returns (bytes32);
}
Once the Interface contract is declared, You need to extend it by using the is
keyword
Syntax
contract DerivedContract is InterfaceContract
Here is an example
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 snippets give 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); }
}
- Constructors 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); }
}