Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java erasure error with unrelated generic in method

Tags:

java

generics

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) {}
  }
}
like image 891
Brian Deterling Avatar asked Jun 01 '09 18:06

Brian Deterling


2 Answers

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.

like image 132
Daniel Martin Avatar answered Oct 20 '22 07:10

Daniel Martin


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.

like image 42
jjnguy Avatar answered Oct 20 '22 07:10

jjnguy