Dart Interfaces

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.

Implementing an Interface

Syntax:

class ClassName implements InterfaceName  

In the following example, we are declaring a class Employee. Implicit, the Engineer class implements the interface declaration for the Employee class.

class Employee
{
void display() {
print(“I am working as an engineer”);
}
}
// Defining interface by implanting another class
class Engineer implements Employee
{
void display() {
print(“I am an engineer in this company”);
}
}
void main()
{
Engineer eng = new Engineer();
eng.display();
}

Output:

I am working as engineer

Explanation
 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.

Leave a comment

Your email address will not be published. Required fields are marked *