3

Why it is possible to compile class with two methods with equal signatures?
"foo" methods have only different return types.
But return type is not a part of method signature in java.
Does java compiler creates bridge methods in this case?
If yes - how real code will look like?

There are following warnings for foo methods:

Method foo(GenClass) has the same erasure foo(GenClass) as another method in type test

If uncomment bar methods, there will be following errors for bar methods:

Method bar(GenClass) has the same erasure bar(GenClass) as another method in type test

class GenClass<T> {

}
public class test {
    public static void main(String[] args) {

    }

    public static Integer foo(GenClass<Integer> criteria) {
        System.out.println("Integer");
        return null;
    }

    public static String foo(GenClass<String> criteria) {
        System.out.println("String");
        return null;
    }

    /*public static void bar(GenClass<Integer> criteria) {
        System.out.println("Integer");
    }

    public static void bar(GenClass<String> criteria) {
        System.out.println("String");
    }*/
}

D:\tools\java\jdk1.6.0_37_32\bin>java -version
java version "1.6.0_38"
Java(TM) SE Runtime Environment (build 1.6.0_38-b05)
Java HotSpot(TM) 64-Bit Server VM (build 20.13-b02, mixed mode)

Volodymyr Bezuglyy
  • 16,295
  • 33
  • 103
  • 133
  • For me it is not possible to compile your code. `Error:(33, 19) java: name clash: foo(designPatterns.singleton.GenClass) and foo(designPatterns.singleton.GenClass) have the same erasure` – Radek Mar 19 '15 at 14:39
  • Yes it is possible... – drgPP Mar 19 '15 at 14:41
  • take a look at this question: http://stackoverflow.com/questions/1998544/method-has-the-same-erasure-as-another-method-in-type – Radek Mar 19 '15 at 14:47
  • 1
    This code does not compile using JDK7 or JDK8. However, in older version, it just generates a warning. – Patrick Mar 19 '15 at 14:47
  • This definitely has nothing to do with [bridge methods](http://docs.oracle.com/javase/tutorial/java/generics/bridgeMethods.html#bridgeMethods). – Radiodef Mar 19 '15 at 18:35

1 Answers1

7

There was a bug in javac Java 6 which made this work, but other Java compilers for Java 6 as well as Java compilers in Java 7+ will throw compile errors.

See this other posts for more details:

Does a method's signature in Java include its return type?

http://vanillajava.blogspot.co.uk/2011/02/with-generics-return-type-is-part-of.html

EDIT

@Radek has posted another good Stackoverflow post in the comments section:

Method has the same erasure as another method in type

EDIT 2 I think I found the bug ticket here: http://bugs.java.com/view_bug.do?bug_id=6182950

Community
  • 1
  • 1
dkatzel
  • 31,188
  • 3
  • 63
  • 67