问题
I'm trying to understand the name clash error I get with the following code:
import java.util.*;
import javax.swing.*;
class Foo<R extends Number> {
public void doSomething(Number n, Map<String, JComponent> comps) {
}
}
class Bar extends Foo {
public void doSomething(Number n, Map<String, JComponent> comps) {
}
}
Error message:
error: name clash:
doSomething(Number,Map<String,JComponent>)
inBar
anddoSomething(Number,Map<String,JComponent>)
inFoo
have the same erasure, yet neither overrides the other
I know I can fix it by either remove the generic type from Foo
, or by changing the Bar
declaration to class Bar extends Foo<Integer>
; what I want to know is why this error occurs in the specific case, but goes away if I remove the comps
parameter from each method. I've done some reading about type erasure, but it still appears to me that both methods should have the same erasure with or without generics, and therefore be a valid override in either case. (Note that I haven't even used the generic parameter anywhere yet, which is why I'm so surprised.)
I know that I've added generic types to parent classes before but only got warnings about the subclasses, not errors. Can anyone explain this scenario?
回答1:
Luiggi is right in the comments. This is a consequence of raw types.
The supertype of a class may be a raw type. Member accesses for the class are treated as normal, and member accesses for the supertype are treated as for raw types. In the constructor of the class, calls to super are treated as method calls on a raw type.
This applies when invoking a supertype method, but also when overriding one.
Take for example, the following
class Bar extends Foo {
public Bar() {
doSomething(1, new HashMap<Number, String>());
}
}
You'll notice that it compiles, even though HashMap<Number, String>
is not a type that is assignable to Map<String, JComponent>
.
The type of a constructor (§8.8), instance method (§8.4, §9.4), or non-static field (§8.3) of a raw type
C
that is not inherited from its superclasses or superinterfaces is the raw type that corresponds to the erasure of its type in the generic declaration corresponding toC
.
(Note that C
in our case is Bar
.)
And the same thing happens when trying to override a method. When trying to override the Foo#doSomething(..)
method, your Bar
class is actually seeing it declared as
public void doSomething(Number n, Map comps) {
}
In other words, every usage of type parameters is erased. So attempting to declare the method
public void doSomething(Number n, Map<String, JComponent> comps) {
}
in the subtype Bar
is actually an attempt at overloading, not overriding. And this fails because of type erasure. The proper override, which you can verify with @Override
, is
public void doSomething(Number n, Map comps) {
}
Further reading:
- What is a raw type and why shouldn't we use it?
来源:https://stackoverflow.com/questions/27230928/name-clash-when-overriding-method-of-generic-class