Dart InterfacesAn 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 InterfaceDart 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 InterfaceTo 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. Syntax: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. Example -Output: I am working as engineer ExplanationIn 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 InheritanceWe 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. Syntax:Let's understand the following example. Example -Output: I am Handscomb My age is 25 I am a professor of Data Structure My salary is 50000 Explanation: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
Next TopicDart Exceptions |