How to use the implements keyword in Dart?
Dart implements keyword
The implements keyword is used to force functions to be redefined in order to implement an interface.
An interface defines methods but does not implement them. Interface declaration does not have a syntax in Dart. Dart considers class definitions to be interfaces. To use an interface, classes need to use the implements keyword.
It forces us to override all methods of the class it implements.
Note: In Dart, we can implement as many classes as needed. We use commas to separate the different instances of implementation.
Code
The following code shows how to use the implements keyword in Dart.
class Shape {void display() {print('Method in Shape class');}}class Triangle implements Shape {// inherited method@overridevoid display() {print('This is the method of the impemented class');}// create methodvoid message(){print('Method in Triangle class');}}void main() {// Instance of Class Trianglevar triangle = Triangle();// Invoke method of class Shape// using class Triangle instancetriangle.display();// Invoke method of class Shapetriangle.message();}
Explanation
- Lines 1–5: We create a class named
Shapewith a methoddisplay(). - Lines 7–17: We create another class named
Trianglethat implements the properties of the classShape. - Lines 19–28: In the
main()function, we create an instance of classTrianglenamedtriangle. Next, we call the method inherited from classShapeusingtriangle. Also, we invoke the method defined in classTriangleusing its instance.