In the example below I was hoping sum getter would return 8, but it is a compile error.
Class 'B' has no instance getter 'sum'.
According to the spec:
Using an abstract class instead of an interface has important advantages. An abstract class can provide default implementations; it can also provide static methods, obviating the need for service classes such as Collections or Lists, whose entire purpose is to group utilities related to a given type.
What is the correct way to provide a default implementation of sum that adds x and y?
abstract class A {
int get x;
int get y;
int get sum => x+y;
}
class B implements A {
int get x => 3;
int get y => 5;
}
main() {
B b = new B();
print(b.x);
print(b.sum); // Not working, why not 8?
}
You have to make B
extend A
instead of implement.
abstract class A {
int get x;
int get y;
int get sum => x+y;
}
class B extends A {
int get x => 3;
int get y => 5;
}
main() {
B b = new B();
print(b.x);
print(b.sum); // displays 8
}
Alternatively if you don't want to use extends because your class may already extend an other class, you can use mixins :
abstract class M {
int get x;
int get y;
int get sum => x+y;
}
class A {
String s = "s";
}
class B extends A with M {
int get x => 3;
int get y => 5;
}
main() {
B b = new B();
print(b.s);
print(b.x);
print(b.sum); // displays 8
}
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