Sobes.tech
Middle

What are the differences between an abstract class and a mixin in Dart?

sobes.tech AI

Answer from AI

Abstract class:

  • Cannot be instantiated directly.
  • Can contain abstract methods (without implementation) and implemented methods.
  • Classes inherit from an abstract class using the extends keyword.
  • A class can only inherit from one class (single inheritance).

Mixin:

  • Cannot be instantiated directly.
  • Cannot have constructors.
  • Can contain implemented methods, but cannot have abstract methods (until Dart 2.1, where abstract mixins appeared).
  • Classes use the functionality of mixins with the with keyword.
  • A class can use multiple mixins.
  • Used for code reuse and adding functionality to classes without inheritance. Essentially, it allows "mixing in" behavior.

Example of an abstract class:

abstract class Animal {
  void makeSound(); // Abstract method
  void eat() {
    print('Eating...');
  }
}

class Dog extends Animal {
  @override
  void makeSound() {
    print('Woof!');
  }
}

Example of a mixin:

mixin CanJump {
  void jump() {
    print('Jumping!');
  }
}

class Cat with CanJump { }

Comparison in tabular form:

Attribute Abstract Class Mixin
Instantiation No No
Constructor Can have Cannot have
Abstract methods Can have Cannot have (until Dart 2.1)
Implemented methods Can have Can have
Usage extends with
Inheritance/Usage Single inheritance Multiple usage
Purpose Define a common contract Code reuse, adding behavior