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.
Note: We must use the
implements
keyword since Dart does not offer a simple means to build inherited classes.
class Interface_class_name{
...
}
class Class_name implements Interface_class_name {
...
}
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();}
Shape
class with a method display()
.Triangle
class that implements the class Shape
.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 theextends
keyword.