I have several classes that all extend the same abstract class Encoder
. The abstract class requires its children to override an abstract method which accepts a generic-typed parameter ( Subscriber<T>
in this example). Each subclass overriding this method uses a different type for this parameter.
abstract class Encoder<T> {
protected String mSomeArg;
public Encoder(String someArg) {
mSomeArg = someArg+" super";
}
public abstract void start(Subscriber<T> subscriber);
}
class ExampleEncoder extends Encoder {
public ExampleEncoder(String arg) {
super(arg); // how to make super class get generic type?
// eg: new Encoder<Message>(arg)
}
@Override
public void start(Subscriber<Message> subscriber) {
Message msg = new Message("hi "+mSomeArg);
subscriber.event(msg);
}
}
Sample use case:
Encoder sample = new ExampleEncoder();
sample.start(new Subscriber<Message>() {
@Override
public void event(Message msg) {
Log(msg.text());
}
});
Encoder otherSample = new OtherEncoder();
sample.start(new Subscriber<OtherThing>() {
@Override
public void event(OtherThing thing) {
Log(thing.toString());
}
});
Question: How can each subclass call its super()
with the generic type it requires for this abstract method?
Note: Using Subscriber<?>
in this abstract method for this example would defeat my purpose of using generics. Also, instantiating each subclass with the generic type it requires (eg: new ExampleEncoder<Message>()
) seems like a plausible workaround, but also seems unnecessary
This
class ExampleEncoder extends Encoder {
is a raw-type . I'm fairly sure you wanted something like
class ExampleEncoder extends Encoder<Message> {
if you want the concrete class to also be generic then you could use
class ExampleEncoder<T> extends Encoder<T>
but you'd need to modify start
to take a Subscriber<T>
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.