I have an interface:
public static interface Consumer<T> {
void consume(T t);
}
And I want to be able to have:
public static class Foo implements Consumer<String>, Consumer<Integer> {
public void consume(String t) {..}
public void consume(Integer i) {..}
}
It doesn't work - the compiler doesn't let you implement the same interface twice.
The question is: Why?
People have asked similar questions here, but the answer was always "type erasure", i.e. you cannot do it because the types are erased at runtime.
And they aren't - some types are retained at runtime. And they are retained in this particular case:
public static void main(String[] args) throws Exception {
ParameterizedType type = (ParameterizedType) Foo.class.getGenericInterfaces()[0];
System.out.println(type.getActualTypeArguments()[0]);
}
This prints class java.lang.String
(if I only keep Consumer<String>
in order to compile)
So, erasure, in its simplest explanation, is not the reason, or at least it needs elaboration - the type is there, and also, you don't care about the type resolution, because you already have two methods with distinct signature. Or at least it seems so.