tags:

views:

483

answers:

2

I've read the other questions related to erasures, but I'm still not clear why I get the compile error in the class below. The other questions involve methods that actually use the generic type, whereas I'm just trying to implement a method using the exact same signature. Can anyone explain?

Compile error -> name clash: bar(java.util.Set) in test.Baz and bar(java.util.Set) in test.Foo have the same erasure, yet neither overrides the other

import java.util.Set;

public class test {
  public interface Foo<T> {
    public void bar(Set<String> s);
  }

  public abstract class Baz implements Foo {
    public void bar(Set<String> s) {}
  }
}
+4  A: 

I think you need to change this:

public abstract class Baz implements Foo {

to this:

public abstract class Baz implements Foo<T> {

That way you properly override function Foo.

jjnguy
+5  A: 

Did you intend for Baz to implement Foo<String> or to implement Foo<T> or to implement Foo? What you typed was the last of those, but this means that Bar implements the "ungenerified" Foo. The weird thing is that this turns off generics in Foo's definition entirely, not just the generics that have to do with T.

That means that inside Baz, the method Foo.bar takes a parameter of just Set, not Set<String>.

You want either:

public abstract class Baz implements Foo {
  public void bar(Set s) {}
}

or

public abstract class Baz<T> implements Foo<T> {
  public void bar(Set<String> s) {}
}

or

public abstract class Baz implements Foo<Void> {
  public void bar(Set<String> s) {}
}

Depending on what you're trying to do.

Daniel Martin
+1 for explaining why it's wrong.
Michael Myers
hehe, I was going to try to explain why it was wrong too...but I don't really know why. :(
jjnguy
Well, you got your answer in several minutes before I got mine in, so you grabbed the "look at the one answer there and if it's even vaguely right upvote it" bump, which is worth from +2 to +7, depending on question and time of day. (And you know your answer won't compile either, right?)
Daniel Martin
Baz is abstract, so I was going to let the concrete subclasses choose T. Your second option is probably the closest to what I meant to do. And yes, it is weird that it turns of all generics, instead of just T. That's what had me stumped. Thanks.
Brian Deterling