Reputation: 3506
If I do this:
abstract class Base {
void doSomething();
}
class Sub extends Base {
}
I'll get a warning in my IDE that I haven't implemented doSomething
in Sub
. How do I do that same thing for properties. Let's say I have a class like this:
class BaseChannel {
void connect() {
Socket.connect(topic);
}
}
class PostChannel extends BaseChannel {
}
PostChannel
hasn't implemented a topic
property here. Is there a way to do something in BaseChannel
that signals that PostChannel
needs to?
Upvotes: 1
Views: 1142
Reputation: 71623
If you want all subclasses to implement a topic
getter, you need to declare one as part of the interface of the superclass. Like you can declare an abstract method, you can also declare abstract fields and getters/setters.
Example:
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);
}
With Dart 2.12 you will also be able able to declare "abstract fields":
abstract final String topic;
or (if it needs a setter too)
abstract String topic;
This will be equivalent with declaring an abstract getter, or an abstract getter/setter pair.
Upvotes: 4
Reputation: 11200
Two options. Separately for getters and setters. It depends on what you need.
abstract class BaseChannel {
String get tipic;
void set topic(String topic);
}
class PostChannel extends BaseChannel {
//
}
Error:
Missing concrete implementations of 'getter BaseChannel.tipic' and 'setter BaseChannel.topic'.
Try implementing the missing methods, or make the class abstract.
You will need to implement some of this:
It all depends on what you declare abstract in the base class (getter, setter or both).
Upvotes: 0