Ran in un problema interessante; la seguente classe compila:Generici in metodi sovrascritti
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 {}
}
ma questo non riesce:
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 {}
}
con questo errore:
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
avrei pensato che a causa di cancellazione del tipo che questi sarebbero essenzialmente identici. Qualcuno sa cosa sta succedendo qui?
Cosa significa "A a = new A <>();'? Che ne dite di 'A a = new A ();'? –
Trinimon
@Trinimon Questa è solo una notazione abbreviata Java7 per A a = new A (); –