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 implements keyword 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 Shape
class Triangle implements Shape {
void display() {
print('This is the method of the impemented class');
}
}
void main() {
// creating instance of Class Triangle
var triangle = Triangle();
// Invoke method of class Shape
// using class Triangle instance
triangle.display();
}

Explanation

  • Lines 1 to 5: We create a Shape class with a method display().
  • Lines 10 to 15: We create another Triangle class that implements the class Shape.
  • Lines 17 to 24: In the main() function, we create an instance of class Triangle named triangle. Next, we call the method inherited from class Shape using triangle.

Note: To use an interface method, a class should use the implements keyword instead of the extends keyword.

Free Resources