tags:

views:

150

answers:

2

As a followup to this question, first the background

Given a class with this declaration:

public class SomeClass<T>

And a subclass that does not use the generic parameter:

public class SomeSubClass extends SomeClass

A method on SomeClass declared as follows:

protected Map<String, Object> getMap(Object param) {
}

If the subclass calls the method like this:

Map<String, Object> val = getMap(param);

The compiler complains in essence that getMap returns a plain Map and there is an unchecked assignment to a genericized Map. Why is this the case? Is this a documented expectations with Generics, and is there a reason for it?

+1  A: 

I don't quite know the rationale for this, but this behavior is specified in the Java Language Specification JLS S4.8:

The superclasses (respectively, superinterfaces) of a raw type are the erasures of the superclasses (superinterfaces) of any of its parameterized invocations.

Given that it's highly discouraged to use Raw types in new code, they wanted to simply the rules for interaction between Raw and Parameterized types I guess.

notnoop
I think the rationale would go something along the lines of it would require a lot of obscure rules + raw types should not be encouraged.
Tom Hawtin - tackline
+1  A: 

It's a weird one. It seems, though, you could always get rid of the error without introducing any problems by extending SomeClass<Object> instead of SomeClass:

public class SomeSubClass extends SomeClass<Object> {
    ...
}
Samir Talwar
Mostly true but not quite. For an expression like 'SomeClass<String> obj = new SomSubClass()', the expression is valid when using raw super type but invalid when using SomClass<Object> as supertype.
notnoop
True, but if you're assigning to a generic object, your class should be generic. Your Java compiler will give a warning about that line, and rightfully so.
Samir Talwar