homik
homik

Reputation: 563

java extending Generic types ambiguous method call

I have run into a problem which is hard for me to understand why this happens.

I have a generic class B which extends generic class A and i have two methods accepting A and B. From method accepting A i want to call method with paramter B but this results in compilation error:

Ambiguous method call. Both method (A) in Main and method (B) in Main match

Here is a code snippet:

public class Main {

private static class A<T> {

}

private static class B<T> extends A {

}

public String method(A<String> arg) {
    return method((B<String>) arg));
}

public String method(B<String> arg) {
    return "some result";
}
}

However if I remove generic type from type A it compiles:

public class Main {

private static class A<T> {

}

private static class B<T> extends A {

}

public String method(A arg) {
    return method((B<String>) arg));
}

public String method(B<String> arg) {
    return "some result";
}
}

What is the reason of that ?

Edit: This issue is somehow related to java 8 because this code is compilable with JDK7

Upvotes: 1

Views: 456

Answers (1)

Alberto S.
Alberto S.

Reputation: 7649

Your class B extends A but it's not specifying its bounds nor any generic info

What I mean is that your line

private static class B<T> extends A { ... }

is equivalent to

private static class B<T> extends A<Object> { ... }

By changing it to

private static class B<T> extends A<T> { ... }

Your code will compile

Upvotes: 2

Related Questions