Is there a way to avoid inheritance in Dart? I'm looking for something like
final class MyJavaClass {
...
}
You can prevent a class from being subclassed by using the final keyword in the class's declaration. Similarly, you can prevent a method from being overridden by subclasses by declaring it as a final method. An abstract class can only be subclassed; it cannot be instantiated.
Multiple Inheritance: When a class inherits more than one parent class than this inheritance occurs. Dart doesn't support this.
No, Dart does not support multiple implementation inheritance. Dart has interfaces, and like most other similar languages it has multiple interface inheritance. For implementation, there is only a single super-class chain that a class can inherit member implementations from.
Not directly, no.
You could write a class with private constructors and access them via static methods:
class MyFinalClass {
MyFinalClass._ctor1() {}
MyFinalClass._ctor2(String param1, String param2) {}
static MyFinalClass getInstance() {
return new MyFinalClass._ctor1();
}
static MyFinalClass getInstanceWithParams(String param1, String param2) {
return new MyFinalClass._ctor2(param1, param2);
}
}
But this has multiple problems:
new
keyword.Ultimately, these are quite a few drawbacks for this feature. It's up to you to decide if it is really worth it.
EDIT
Contrary to what I have written before, factory constructors would also work, eliminating the "unable to instantiate with new
keyword" drawback.
class MyFinalClass {
factory MyFinalClass.ctor1() {}
factory MyFinalClass.ctor2(String param1, String param2) {}
void method1() {}
void method2() {}
}
Also, to illustrate why the ability to implement the not-so-final class is a big problem:
class Sub implements MyFinalClass {
MyFinalClass _d;
Sub.ctor1() {
_d = new MyFinalClass.ctor1();
}
Sub.ctor2(String p1, String p2) {
_d = new MyFinalClass.ctor2(p1,p2);
}
void method1() => _d.method1();
void method2() {
// do something completely different
}
}
This pseudo-subclassing would work with the static method variant as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With