Implicit interface in Dart with examples

Published by admin on

Dart implicit interface with examples

Implicit interface in Dart :

Dart doesn’t have any interface keyword to define an interface. In Dart, each class implicitly defines an interface. This interface holds all the instance members of the class and of any other classes it implements.

In this post, I will show you how to use implicit interface in Dart with examples.

 

How to use implicit interface :

We can use impliments keyword to implement one implicit interface or class. We can implement one or multiple classes.

 

Example to implement a single interface :

Let’s consider the below example :

class Vehicle {
  String type = 'Vehicle';

  String printDetails() => 'Type of vehicle : $type';
}

class Audi implements Vehicle {
  @override
  String type = 'Car';

  @override
  String printDetails() => 'Type of Audi : $type';
}

void main() {
  var audi = Audi();
  var vehicle = Vehicle();
  print(vehicle.printDetails());
  print(audi.printDetails());
}

 

Explanation :

Here, we have two classes Vehicle and Audi. Class Vehicle has one string variable type and one method printDetails to print one detail message. Class Audi is implementing the implicit interface of Vehicle. As you can see, we are using the override annotation to override class variables and methods.

If you run the above program, it will print the below output :

Type of vehicle : Vehicle
Type of Audi : Car

Dart implicit interface example

 

Example to implement multiple interfaces :

We can also implement multiple interfaces. Instead of just one class name, put all class names separated by comma. That’s it.

 

class Vehicle {
  String type = 'Vehicle';

  String printDetails() => 'Type : $type';
}

class Color {
  String printColor() => 'Color can be anything';
}

class Audi implements Vehicle,Color {
  @override
  String type = 'Car';

  @override
  String printDetails() => 'Type : $type';

  @override
  String printColor() => 'Red';
}

void main() {
  var audi = Audi();
  var vehicle = Vehicle();
  var color = Color();

  print(vehicle.printDetails());
  print(color.printColor());
  print(audi.printDetails());
  print(audi.printColor());
}

Explanation :

Here, Audi class is implementing two implicit interfaces: Vehicle and Color. Audi class is overriding every method and variables of both classes. If you run this program, it will print the below output :

Type : Vehicle
Color can be anything
Type : Car
Red

Similar tutorials :

Categories: dart

0 Comments

Leave a Reply

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