So I have an interface -
public interface GenericTranslator <From, To> {
To translate(From from);
}
and have a class that implements it
public class TimeToStringTranslator implements GenericTranslator <Time, String> {
String translate(Time time) { ... }
}
But I now want to have an abstract layer where input type From
is Time
// an abstract class with partial generic defined
public abstract class AbstractTimeTranslator<Time, To> implements GenericTranslator<Time, To> {
@Override
To translate(Time time) {
doSomething();
return translateTime(time);
}
protected abstract To translateTime(Time time);
}
// concrete class
public class TimeToStringTranslator extends AbstractTimeTranslator<Time, String> {
String translateTime(Time time) { .... }
}
Is it possible in Java? I tried, Java treats Time
as a generic name in AbstractTimeTranslator
If Time
is an actual type argument instead of another generic type parameter, then you should not declare Time
as a generic type parameter in the class definition of AbstractTimeTranslator
; just use it as a type argument in the implements
clause.
This only defines the To
type parameter in this class.
abstract class AbstractTimeTranslator<To> implements GenericTranslator<Time, To> {
Consequently, you only need to supply one type argument in the extends
clause of the concrete subclass.
class TimeToStringTranslator extends AbstractTimeTranslator<String> {
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