Hi,

I am probably missing something. The following compiles:

public class Generics {

  public static void main(String[] args) {
    method1(new Foo<SubBar<?>>());
    method2(new Foo<SubBar<?>>());
  }
static Object method1(Foo<? extends Bar<?>> y) {
    return null;
  }
static <S extends Bar<?>> Object method2(Foo<S> y) {
    return null;
  }
static class SubBar<T> extends Bar<T> {
  }
static class Bar<T> {
  }
static class Foo<T> {
  }
}

Can you clarify which part should be different for me to have the same results
as you?

Regards,
Ismael

I thought I could, but it seems I did one simplification too many. :-)

I.e., you get a compile error when trying to pass a Foo<Bar<String>> to the method:

        static Object method1(Foo<Bar<?>> y)

because Foo<Bar<String>> is not a subtype of Foo<Bar<?>>. I thought the same applied to Foo<? extends Bar<?>>, i.e., that Foo<SubBar<String>> would not apply (whereas Foo<SubBar<?>> would. Thus I thought, well all you got to do is replace the ? in the new's by String and that should cause the compiler to reject it.

But it turns out the binding of the second ? in Foo<? extends Bar<?>> means that the first ? must be subtype of Bar<?> (i.e., Bar<String> is a subtype of Bar<?>), and it does not mean that the whole must be a subtype of Foo<AnySubClassOfBar<?>>. Argh.

Thus it is the case, it seems, that:

        Foo<? extends Bar<?>>

means A Foo of (any subtype of Bar<?>). Since this compiles (albeit with a warning):

        Bar<?> x = new SubBar()

it means that SubBar is a subtype of Bar<?>>. Thus you would indeed expect to be able to pass a Foo<SubBar> to a method accepting Foo<? extends Bar<?>>.

But you can't.

So thanks for your critical reading, and I'm back to square 1. Either it's a bug or else I don't understand (or both). :-)

Regards,
Sebastiaan




Attachment: smime.p7s
Description: S/MIME Cryptographic Signature

Reply via email to