1

(First, I apologize if some of this phrasing is awful, I'm not sure what to call some of these things, leave a comment if you have a better idea and I can edit.)

Today I ran into an issue like below in Example1. If you have a generic that is declared as having a child of the generic's allowed types (Foo<Bazz> foo = new Foo<Bazz>();) it will make a compile-time error if you give it to a method that takes only the generic's parent type (method1(Foo<Bar> foo)).

public class Example1 {

    public static void main(String[] args) {
        Foo<Bazz> foo = new Foo<Bazz>();
        method1(foo); // Compilation error below
    }

    public static void method1(Foo<Bar> foo) {
    {}

    public static class Foo<B extends Bar>
    {}

    public static class Bar
    {}

    public static class Bazz extends Bar
    {}
}

Error: The method method1(Example1.Foo<Example1.Bar>) in the type Example1 is not applicable for the arguments (Example1.Foo<Example1.Bazz>)

This is very odd to me, because the following works fine. You can make some object that is a child type (Child c = new Child();) and methods that accept the parent (method2(Parent p)) will still accept it just fine.

public class Example2 {

    public static void main(String[] args) {
        Child c = new Child();
        method2(c);
    }

    public static void method2(Parent p)
    {}

    public static class Parent
    {}

    public static class Child extends Parent
    {}
}

Why can I pass child types into parameters asking for parent types but not generics with child types into parameters asking for generics with parent types?

I'm sure it's just some standard, but why? Is a Foo<Bazz> not a Foo<Bar> in a similar manner to a Bazz being a Bar?

Captain Man
  • 6,997
  • 6
  • 48
  • 74

0 Answers0