Dart: extends vs implements vs with

a short way to understand mixins

Manoel Soares Neto
2 min readApr 22, 2020

--

1⃣️ Using extends

🤔 Do you know inheritance?

Inheritance allows us to create new classes that reuse, extend and/or modify pre-existing classes behavior. The pre-existing class is called superclass and the new class we're creating is called derived class. In Dart, we can inherit only one superclass, but inheritance is transitive. If the class Hatch is derived from the class Car and this class is derived from class Vehicle, then Hatch will be derived from Vehicle. Use extends to create derived class, and super when you want to refer to the superclass.

When class Car extends Vehicle, all properties, variables, functions implemented in class Vehicle will be available in class Car.

Also is possible to overwrite superclass functions.

So: You use extends when you want to create a more specific version of a class.

2⃣️ Using implements

Suppose you want to create your own Car class, without inhering all the properties, variables and functions of the Vehicle class, but you want to inherit only the Vehicle type. To do this, the Car class must implement the Vehicle interface.

Dart allows you to implement multiple classes or interfaces.

✍️ Example

Imagine that you need to implement a bird and a duck, both are animals, but the bird can only fly and the duck can fly and swim. We'll do this using what we know so far.

First, we'll create superclass and the behaviors:

Now, we'll create Bird and Duck, implementing proper behaviors:

Note, that using implements we had to implement fly and swim functions, repeating code! It was not possible to inherit the the behavior implementations this way. Is there a way to reuse the code for these behaviors? Yes, we'll see next!

3⃣️ Using with

Mixin is a different type of structure, wich can only be used with the keyword with and is used to include common code snippets, I'd say, reuse the code.

Mixins are a way of reusing a class’s code in multiple class hierarchies (dartlang.org).

Here is how mixins perform the previous implementation:

You can replace abstract class to mixin if you prefer.

Mixins are a way to abstract and reuse a family of operations and state, it is similar to the reuse you get from extending a class, but is not multiple inheritances, there still only one superclass. They work by putting the mixin implementation on top of the superclass to create a new class. In the example above, it is possible to rewrite a function, mixins allows this.

✌️Thanks

That was my first story on Medium, I hope you liked 😃.

I would like to thank Romain Rastel for the incredible story about mixins, I advise you to read to understand even more about this subject.

Any questions, feel free to ask below.

--

--