Let's say we have two classes Parent and Child:
public class Parent {
}
public class Child extends Parent {
}
And we have method with following argument:
public void foo(List<Parent> list) {
...
}
My question why is following method arguments is illegal(case A)
List<Child> list = List.of(new Child());
foo(list); //compile error
but at the same time such case is valid(case B)
foo(List.of(new Child());
List.of() has such signature static <E> List<E> of(E... elements), so i expect that
List.of(new Child()) has type List<Child> and because of this wildcard rule(List<Child> not extends List<Parent>) i think that both cases must not compile.
But why case B compiles? Compiler sees, that List.of(new Child()) doesn't have explicit type and checks that every item of list can be casted to Parent.class and do it to obtain correct type?
foo(List<? extends Parent> list)to accept descendants of Parent.