【发布时间】:2013-04-04 04:04:20
【问题描述】:
遇到了一个有趣的问题;以下类编译:
public class Test {
public static void main(String[] args) throws Exception {
A a = new A();
B b = new B();
foo(a);
foo(b);
}
private static void foo(A a) {
System.out.println("In A");
}
private static void foo(B b) {
System.out.println("In B");
}
private static class A {}
private static class B extends A {}
}
但是这个失败了:
public class Test {
public static void main(String[] args) throws Exception {
A<String> a = new A<>();
B b = new B();
foo(a);
foo(b);
}
private static void foo(A<String> a) {
System.out.println("In A");
}
private static void foo(B b) {
System.out.println("In B");
}
private static class A<T> {}
private static class B extends A {}
}
出现此错误:
Test.java:8: error: reference to foo is ambiguous, both method foo(A<String>) in Test and method foo(B) in Test match
foo(b);
^
Note: Test.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
1 error
我原以为由于类型擦除,这些将基本相同。有人知道这里发生了什么吗?
【问题讨论】:
-
A<String> a = new A<>();是什么?A<String> a = new A<String>();怎么样? -
@Trinimon 这只是 Java7 A
a = new A (); 的简写符号;
标签: java generics overloading