Junior — Middle
What is the purpose of the mixin concept in object-oriented programming?
sobes.tech AI
Answer from AI
A mixin is a way to reuse code in object-oriented programming, allowing you to add functionality to a class without using inheritance.
The main purpose of a mixin is to extend a class with additional methods and properties without creating a deep inheritance hierarchy. This is especially useful when you need to add common capabilities to different classes.
In Dart (and Flutter), a mixin is declared using the mixin keyword and applied to classes with the with keyword.
Example:
mixin Logger {
void log(String message) {
print('Log: $message');
}
}
class User with Logger {
String name;
User(this.name);
}
void main() {
var user = User('Alice');
user.log('User created'); // Using method from mixin
}
Thus, a mixin allows adding functionality without the need to inherit from a base class.