What is Interface and How to use it.
In dart there is no keyword like interface , while in other programming language we can see that interface keyword.
So ,in Dart, every class is implicit interface. An interface defines a syntax that a class must follow.
There only minor change between inheritance and interface . Like if we want to use inheritance at that time we use " extend " keyword and for the interface we use " implements " .
In interface we can not use parent class method like inheritance , so we can not use super keyword when we use implements keyword.
we can use multiple implements in dart
Let's understand with example .
// Objectives // 1. Interface void main() { var tv = Television(); tv.volumeUp(); tv.volumeDown(); tv.justAnotherMethod(); } class Remote { void volumeUp() { } void volumeDown() { } } class AnotherClass { void justAnotherMethod(){ } } // Here Remote and AnotherClass acts as Interface class Television implements Remote, AnotherClass { void volumeUp() { // super.volumeUp(); // Not allowed to call super while implementing a class as Interface print("______Volume Up in Television_______"); } void volumeDown() { print("______Volume Down in Television_______"); } void justAnotherMethod() { print("Some code"); } }
Difference Between Extends & Implements
- | extends | implements | | --- | --- | | Used to inherit a class in another class. | Used to inherit a class as an interface in another class. | | Gives complete method definition to sub-class. | Gives abstract method definition to sub-class. | | Only one class can be extended. | Multiple classes can be implemented. | | It is optional to override the methods. | Concrete class must override the methods of an interface. | | Constructors of the superclass is called before the sub-class constructor. | Constructors of the superclass is not called before the sub-class constructor. | | The super keyword is used to access the members of the superclass. | Interface members can’t be accessed using the super keyword. | | Sub-class need not to override the fields of the superclass. | Subclass must override the fields of the interface. |