Middle
What is the difference between an abstract class and a mixin?
sobes.tech AI
Answer from AI
Abstract class:
- Can have both regular and abstract methods and fields.
- Cannot instantiate an abstract class directly.
- Can contain constructors.
- Inherited using the
extendskeyword. Single inheritance is supported. - Used to define common behavior and structure for subclasses.
Mixin:
- Can contain methods and fields, but cannot define constructors.
- Not intended for instantiation.
- Used to add functionality to classes that does not fit into the inheritance hierarchy.
- Combined with a class using the
withkeyword. A class can use multiple mixins.
| Attribute | Abstract class | Mixin |
|---|---|---|
| Instance | Cannot be created directly | Cannot be created |
| Constructors | Can have | Cannot have |
| Inheritance | extends (single) |
with (multiple) |
| Main purpose | Define hierarchy | Add behavior |
Example of using an abstract class:
abstract class LivingBeing {
void breathe(); // Abstract method
void grow() { // Regular method
print('Growing...');
}
}
class Human extends LivingBeing {
@override
void breathe() {
print('Breathing with lungs');
}
}
Example of using a mixin:
mixin Walkable {
void walk() {
print('Walking...');
}
}
mixin Swimmable {
void swim() {
print('Swimming...');
}
}
class Dog with Walkable, Swimmable {
// The Dog class now has walk() and swim() methods
}