Java Generics Name Clash when Extending
I am new to generics and I would appreciate any help I can get with the following problem:
I have this parent class:
publi开发者_如何学Goc class Parent<K, V> {
public void f(K key,V value){}
}
And then I have this child class:
public class Child<K,V> extends Parent<K,LinkedList<V>> {
@Override
public void f(K key,V value) {}
}
Well, the hope was that Child.f
would override Parent.f
, but unfortunately the compiler doesn't like what is going on here and gives me:
Name clash: The method f(K, V) of type Child<K,V> has the same erasure as f(K, V) of type
Parent<K,V> but does not override it
I have seen this error before in different contexts, but I am not sure why it comes up in this particular one. Is there any way of avoiding it?
Thanks in advance.
You are using V for two different meanings. Renaming V to W in the child it should look like this. Here V in the parent is LinkedList<W>
public class Child<K,W> extends Parent<K,LinkedList<W>> {
@Override
public void f(K key,LinkedList<W> value) {}
}
BTW: Does it really have to be a concrete class LinkedList, couldn't it be List.
Edit: Perhaps you are confusing what you need in a specific case with what you want to define as a generic definition. e.g.
public class Child<K,V> extends Parent<K,V> {
@Override
public void f(K key, V value) {}
}
Child<String, LinkedList<String>> child = new Child<String, LinkedList<String>>();
child.f("key", new LinkedList<String>());
Here you have a child which you have defined as taking a LinkedList, but not all Child'ren have to take LinkedLists.
精彩评论