If you create a generic class in Java (the class has generic type parameters), can you use generic methods (the method takes generic type parameters)?
Consider the f
From my comment on MAnyKeys answer:
I think the full type erasure makes sense combined with the mentioned backwards compatability. When the object is created without generic type arguments it can be (or shoudl be?) assumed that the usage of the object takes place in non generic code.
Consider this legacy code:
public class MyGenericClass {
public Object doSomething(Object k){
return k;
}
}
called like this:
MyGenericClass foo = new MyGenricClass();
NotKType notKType = foo.doSomething(new NotKType());
Now the class and it's method are made generic:
public class MyGenericClass {
public K doSomething(K k){
return k;
}
}
Now the above caller code wouldn't compile anymore as NotKType is not a suptype of KType. To avoid this the generic types are replaced with Object. Although there are cases where it wouldn't make any difference (like your example), it is at least very complex for the compiler to analyze when. Might even be impossible.
I know this szenario seems a little constructed but I'm sure it happens from time to time.