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
@override
void display() {
print('This is the method of the impemented class');
}
// create method
void message(){
print('Method in Triangle class');
}
}
void main() {
// Instance of Class Triangle
var triangle = Triangle();
// Invoke method of class Shape
// using class Triangle instance
triangle.display();
// Invoke method of class Shape
triangle.message();
}

Explanation

  • Lines 1–5: We create a class named Shape with a method display().
  • Lines 7–17: We create another class named Triangle that implements the properties of the class Shape.
  • Lines 19–28: In the main() function, we create an instance of class Triangle named triangle. Next, we call the method inherited from class Shape using triangle. Also, we invoke the method defined in class Triangle using its instance.

Free Resources