Dart Inheritance: Type Interface in a Mixed List

Dart Inheritance: Type Interface in a Mixed List

Table of contents

In Dart, type interface is a powerful feature that allows you to define a common interface for a group of related classes. When dealing with a mixed list containing objects of different types, you can leverage type checking to ensure that each object adheres to the specified interface.

So, in simple words a type interface is like a set of rules or expectations that different objects can follow. Imagine you have a group of toys, each with its own unique features, but they all have something in common, like being able to make a sound. You can create a rulebook, called an interface, that says every toy must have a method to make a sound.

When you have a mixed collection of toys, you can use this rulebook to make sure each toy in the collection follows the same set of rules. This way, even though each toy is different, you can treat them all the same when it comes to making sounds. This ensures that no matter what type of toy you have, you can always expect it to do certain things, like making a sound, because they all adhere to the same interface.


Example:

Consider a scenario where we have a base interface Shape, with subclasses Circle and Square, each implementing the Shape interface.

By utilizing a mixed list, we can collect instances of both Circle and Square objects while ensuring that each object adheres to the Shape interface.

// Define a common interface
abstract class Shape {
  void draw();
}

class Circle implements Shape {
  @override
  void draw() {
    print('Drawing a Circle'); 
  }
}

class Square implements Shape {
  @override
  void draw() {
    print('Drawing a Square');
  }
}

void main() {
  List<Shape> shapes = [Circle(), Square()];

  for (var shape in shapes) {
    shape.draw();
  }
}


Conclusion

In conclusion, Dart's type interface feature empowers developers to create coherent and interoperable code structures, even within mixed lists containing objects of different types.