gpt4 book ai didi

dart - 为抽象类中的方法提供默认实现

转载 作者:行者123 更新时间:2023-12-05 00:29:08 25 4
gpt4 key购买 nike

在下面的示例中,我希望 sum getter 返回 8,但这是一个编译错误。

Class 'B' has no instance getter 'sum'.

根据规范:

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.



提供添加 x 和 y 的 sum 的默认实现的正确方法是什么?
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?
}

最佳答案

你必须做 B延长 A而不是实现。

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
}

或者,如果您不想使用扩展,因为您的类可能已经扩展了另一个类,您可以使用 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
}

关于dart - 为抽象类中的方法提供默认实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17789399/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com