What is an interface in Dart?
Dart interface
An interface specifies the syntax that all classes must follow. An interface defines a set of methods for an object.
The most common usage of the interface is to impose compulsion on a class.
When a class implements an interface, it must override all its methods and instance variables.
The class declaration is also an interface in Dart.
Why use an interface in Dart?
- It is used to achieve abstraction.
- It’s a mechanism to achieve multiple inheritances.
Note: We must use the
implementskeyword since Dart does not offer a simple means to build inherited classes.
Syntax
class Interface_class_name{
...
}
class Class_name implements Interface_class_name {
...
}
Code
The following code shows how to use the interface keyword in Dart:
// class Shape (interface)class Shape {void display() {print('Method in Shape class');}}// class Triangle implementing class Shapeclass Triangle implements Shape {void display() {print('This is the method of the impemented class');}}void main() {// creating instance of Class Trianglevar triangle = Triangle();// Invoke method of class Shape// using class Triangle instancetriangle.display();}
Explanation
- Lines 1 to 5: We create a
Shapeclass with a methoddisplay(). - Lines 10 to 15: We create another
Triangleclass that implements the classShape. - Lines 17 to 24: In the
main()function, we create an instance of classTrianglenamed triangle. Next, we call the method inherited from classShapeusingtriangle.
Note: To use an interface method, a class should use the
implementskeyword instead of theextendskeyword.