An interface defines the syntax that any entity must adhere to. Dart does not have any separate syntax to define interfaces. An Interface defines the same as the class where any set of methods can be accessed by an object. The Class declaration can interface itself.
The keyword implement is needed to be writing, followed by class name to be able to use the interface. Implementing class must provide a complete definition of all the functions of the implemented interface. We can say that a class must define every function with the body in the interface that we want to achieve.
Declaring an Interface
Dart doesn't provide syntax for declaring interface directly. Implicitly, a class declaration itself an interface containing the entire instance member of the class and of any interfaces it implements.
Implementing an Interface
To work with interface methods, the interface must be implemented by another class using the implements keyword. A class which is implemented the interface must provide a full implementation of all the methods that belongs to the interface. Following is the syntax of the implementing interface.
In the following example, we are declaring a class Employee. Implicit, the Engineer class implements the interface declaration for the Employee class. Let's understand the above example by the following code snippet.
I am working as engineer
In the above example, we defined a class Engineer as an interface implementing the Engineer class. Then, we defined the same method display() in both classes. This method override in class Engineer, so we created the object of the Engineer class in a main() function invoked the display() function. It printed the output to the screen.
Implementing Multiple Inheritance
We have discussed previously that the multiple inheritance is not supported by the Dart, but we can apply the multiple interfaces. We can say that, using multiple interfaces, we can achieve multiple inheritance in Dart. The syntax is given below.
Let's understand the following example.
I am Handscomb My age is 25 I am a professor of Data Structure My salary is 50000
In the above example, we implemented multiple interfaces in class College. Each data member of Student and Faculty class is overriding in class College. We created the object of College class and invoked the overriding functions. It printed the result.
Rules for Implementing Interfaces