Middle
Millised on erinevused abstraktse klassi ja mixini vahel Dartis?
sobes.tech AI
Vastus AI-lt
Abstract class:
- Cannot be instantiated directly.
- Can contain abstract methods (without implementation) and implemented methods.
- Classes inherit from an abstract class using the
extendskeyword. - A class can inherit from only 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 mixin functionality with the
withkeyword. - 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:
| Feature | 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, behavior addition |