What is the difference between:
class A {}
class B with A{}
and
mixin A{}
class B with A{}
?
What is the difference between:
class A {}
class B with A{}
and
mixin A{}
class B with A{}
?
In Dart, a class can only extend
one other class. But it can implement
or mixin
as many as you want.
The thing is, when you extend a class, you inherit all its attributes, methods and it's constructors. When you implement a class, if you are adding only methods/attributes that you don't already have, you can simply continue your code. If you are implementing an abstract method, you'll need to actually implement it. Now, mixins are like extended classes, the classes that mix them, are their child as well as with extend and implements, but it has no constructor.
The actual idea for mixins is that you can add functionalities to any class, and they don't have to extend another class. That's why they usually do simple stuff only.
/*normal class u can create constructors create objects from it
and all that good jazz*/
class Foo {
final int a;
Foo(this.a);
void someMethod() {}
}
/*mixin is like a container than hold some
functionalities that you want to mix with an existing class*/
mixin Bar {
void add() {}
}
/* this class extends Foo to inherent some goodness but i need a
functionality that is not directly related to parent child
relationship so i mix it with Bar */
class Baz extends Foo with Bar {
Baz(super.a);
void myMethod() {
// i have access to add function here
add();
}
}
// mixin class act like both
mixin class AnotherClass {
AnotherClass();
}
© 2022 - 2024 — McMap. All rights reserved.