1

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

2
  • Possible duplicate of Compiler error : reference to call ambiguous OR this Commented Sep 21, 2017 at 9:57
  • Well, it does not quite make sense on what you are doing. Anyway: A<String> is-NOT-a A<Object> . As you declare your B<T> extends A, which means B<T> extends A<Object>, which means, B<WhateverType> is-a A<Object>. Given A<Object> is-NOT-a A<String>, B<String> is-NOT-a A<String>, so the compiler is actually complaining it correctly by avoiding you to cast from A<String> to B<String> as it will never be lega Commented Sep 25, 2017 at 2:53

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

You are right it will compile but what if i don't want them to share the types ? I cast the parameter to B to explicitly call the other method but it looks like compiler ignores it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.