I found that in Java I could use anonymous class to implement interface like Runnable (non-generic). I could also declare a variable without specifying type parameter on the right of "=". But I found for generic type, I cannot omit this:
import java.util.ArrayList;
import java.util.List;
interface Normal {
Integer f();
void g();
}
interface Generic<T> {
T f();
void g();
}
public class GenericInterface {
public static void main(String[] args) {
List<Integer> li = new ArrayList<>(); // ArrayList without type parameter, OK
Runnable r = new Runnable() {
@Override public void run() {}
};
Normal n = new Normal() { // declare implementation, OK.
@Override public Integer f() {
return new Integer(0);
}
@Override public void g() {}
};
Generic<Integer> i = new Generic<>() { // Why need type paramter here?
@Override public Integer f() {
return new Integer(0);
}
@Override public void g() {}
};
}
}
As you could see, javac report compilation failure for this line:
Generic<Integer> i = new Generic<>() {
While the compiler is smart enough to compile List<Integer> li = new ArrayList<>(), when compiler already know the real type from the left of this statement, why it still needs me to write new Generic<Integer>() { ?
Or Java prevents generic interface implementation without specifying the type parameter? What is the reason?