I am extending a class defined in a library which I cannot change:
public class Parent { public void init(Map properties) { ... } }
If I am defining a class ‘Child’ that extends Parent and I am using Java 6 with generics, what is the best way to override the init method without getting unchecked warnings?
public class Child extends Parent { // warning: Map is a raw type. References to generic type Map<K,V> should be parameterized public void init(Map properties) { } }
If I add generic parameters, I get:
// error: The method init(Map<Object,Object>) of type Child has the same erasure as init(Map) of type Parent but does not override it public void init(Map<Object,Object>) { ... } // same error public void init(Map<? extends Object,? extends Object>) { ... } // same error public void init(Map<?,?>) { ... }
This error occurs regardless of whether I use a specific type, a bounded wildcard, or an unbounded wildcard. Is there a correct or idiomatic way to override a non-generic method without warnings, and without using @SuppressWarnings(‘unchecked’)?
Yes, you have to declare the overriding method with the same signature as in the parent class, without adding any generics info.
I think your best bet is to add the
@SuppressWarnings('unchecked')annotation to the raw-type parameter, not the method, so you won’t squelch other generics warnings you might have in your own code.