'difference between interface and abstract contract in solidity
I am learning solidity and got to know that interface
and abstract
are both classes that may contain unused functions.
My doubt is: What is the difference between interface
and abstract contract
in a solidity smart contract?
Solution 1:[1]
It's the same as in most other object-oriented programming languages:
- Interface only declares functions. Cannot implement them.
- Abstract class can declare functions (same as interface) as well as implement them.
- Both cannot be instantiated and need to be implemented/inherited from.
Example:
interface IMyContract {
// can declare, cannot implement
function foo() external returns (bool);
}
abstract contract MyContract {
// can declare
function foo() virtual external returns (bool);
// can implement
function hello() external pure returns (uint8) {
return 1;
}
}
Solution 2:[2]
Abstract Contract
Contracts are identified as abstract contracts if at least one of their functions lacks an implementation. This is the only requirement for abstract class. As a result, they cannot be compiled. They can however be used as base contracts from which other contracts can inherit from.
Unlike other languages, Solidity contracts do not need an
abstract
keyword to be marked as abstract. Rather, any contract that has at least one unimplemented function is treated as abstract in Solidity. An abstract contract can be neither compiled nor deployed unless it has an implementing contractcontract MyAbstractContract { function myAbstractFunction() public pure returns (string); }
if a contract inherits an abstract contract and does not implement all the unimplemented functions, then that contract will be considered abstract as well
//MyContract is also abstract contract MyContract is MyAbstractContract { function myAbstractFunction() public pure returns (string) }
But this is not abstract because we are implementing the function.
contract MyContract is MyAbstractContract {
function myAbstractFunction() public pure returns (string)
{ return "string value to return"; }
}
- An
abstract contract
can have both implemented and unimplemented functions.
Interfaces
interfaces can have only unimplemented functions. Also, they are neither compiled nor deployed.
- Interfaces cannot implement any of their functions. All interface functions are implicitly virtual
- Interfaces are defined with the keyword
Interface
. - Interfaces cannot inherit other contracts or interfaces but other contracts can inherit from interfaces.
- Interfaces cannot define a constructor
- Interfaces cannot have state variables
- As of now Interfaces cannot define structs and enums but might change soon.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Petr Hejda |
Solution 2 |