Implementing interface and abstract class with same methode name resulting in generic name clash
-
28-06-2021 - |
Question
public interface Foo <T> {
void setValue(T value);
}
public abstract class Bar extends JFormattedTextField{
@Override
public void setValue(Object value) {
}
}
public class FooBar extends Bar implements Foo<String>{
@Override //Foo
public void setValue(String aValue) {
// TODO Auto-generated method stub
}
@Override //Bar
public void setValue(Object aValue) {
// TODO Auto-generated method stub
}
}
This results in
Name clash: The method setValue(M) of type Foo has the same erasure as setValue(Object) of type JFormattedTextField but does not override it
Why do I get no love from the compiler and how could I fix it?
Solution
This is because of type erasure (see this question: Java generics - type erasure - when and what happens)
In a nutshell: The compiler will use String
to check that all method calls and type conversions work and then, it will use Object
to generate the byte code. Which means you now have two methods with the same signature: public void setValue(Object aValue)
There is no perfect solution for this. You can make the code above compile by using Foo<Object>
instead of Foo<String>
but that's usually not what you want.
A workaround is to use an adapter:
public class FooBar extends Bar {
public Foo<String> adapt() {
return new Foo<String>() {
public void setValue(String value) {
FooBar.this.setValue( value );
}
}
}
}
Basically what the adapt()
method should do is create a new instance which implements the correct interface and which maps all method invocations to this
.
OTHER TIPS
Java uses type erasure for generics. In your case type is String which Subclass of Object also. And your Bar class allows Object so Nameclash happens.
In your scenario because you are using a non generic legacy class with object as parameter in the extended class I will advice you to change method name or change type of Foo
to String
`Back to 1.4 days :-)