Why are generics completely disabled when you ignore a parameter type?
Asked Answered
B

2

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?

Blur answered 24/6, 2009 at 19:43 Comment(3)
Can you post the exact exception and a real code example? It's hard to pinpoint with what you've posted.Membranophone
If you look at the linked question you have a real example. #1040158Blur
Related question with good explanation stackoverflow.com/questions/449103Ohare
F
1

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.

Follansbee answered 24/6, 2009 at 19:53 Comment(1)
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.Strobile
T
1

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> {
    ...
}
Townsville answered 24/6, 2009 at 19:57 Comment(2)
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.Follansbee
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.Townsville

© 2022 - 2024 — McMap. All rights reserved.