Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Partial Generics in Java

Tags:

java

generics

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

like image 633
Kevindra Avatar asked Feb 03 '16 22:02

Kevindra


1 Answers

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> {
like image 193
rgettman Avatar answered Oct 26 '22 00:10

rgettman