2

I am new to generics and I would appreciate any help I can get with the following problem:

I have this parent class:

public 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.

delmet
  • 1,013
  • 2
  • 9
  • 23
  • Why does Child extend `Parent>` and not `Parent`? – DGH Dec 16 '10 at 21:42
  • Because the Parent is a form of a HashMap and the Child a MultiMap. But I need to overwrite certain methods to insure efficiency. Just instantiating a `HashMap>` won't do in my situation. – delmet Dec 16 '10 at 22:02

1 Answers1

2

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.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • The problem is that I don't want to pass a LinkedList to f, I want to pass an object, which I might put into the list myself. At least that is what my intention was. I made it a LinkedList because that would do in my app, and I might need to create new ones. – delmet Dec 16 '10 at 21:56
  • Then it can't be an override. It would have to be two different methods. Any child of Parent for any K and V has to accept a V for the second argument of f. – Dan Dec 16 '10 at 22:03
  • I see. Thanks for your help. That kills polymorphism though, so I will have to find a more elegant solution. – delmet Dec 16 '10 at 22:07
  • How does that in any way kill polymorphism? In fact, this is required for polymorphism. – Falmarri Dec 16 '10 at 22:57