我这样做:
abstract class Base {
void doSomething();
}
class Sub extends Base {
}
我会在我的IDE中得到一个警告,我没有在Sub
中实现doSomething
。如何对属性做同样的事情。假设我有一个这样的类:
class BaseChannel {
void connect() {
Socket.connect(topic);
}
}
class PostChannel extends BaseChannel {
}
PostChannel
在这里没有实现topic
属性。是否有一种方法可以在BaseChannel
中做一些PostChannel
需要做的事情?
如果你想让所有子类都实现topic
getter,你需要声明一个作为超类接口的一部分。就像你可以声明抽象方法一样,你也可以声明抽象字段和getter/setter。
的例子:
abstract class BaseChannel {
String get topic; // Abstract getter declaration.
void connect() {
Socket.connect(topic);
}
}
class PostChannel extends BaseChannel {
final String topic; // Implements the getter.
PostChannel(this.topic);
}
在Dart 2.12中,您还可以声明"抽象字段":
abstract final String topic;
或者(如果也需要setter)
abstract String topic;
这相当于声明一个抽象getter或抽象getter/setter对。
两个选项。分别用于getter和setter。这取决于你需要什么。
abstract class BaseChannel {
String get tipic;
void set topic(String topic);
}
class PostChannel extends BaseChannel {
//
}
错误:
Missing concrete implementations of 'getter BaseChannel.tipic' and 'setter BaseChannel.topic'.
Try implementing the missing methods, or make the class abstract.
你将需要实现其中的一些:
- getter
- setter
- getter和setter <
- 字段/gh>
这完全取决于你在基类中声明的抽象(getter, setter或两者)。