0

Why doesn't this work? I thought the list would be able to accept any object that is an instance of A.

import java.util.List;

public class Test {

    interface A {}

    interface B extends A {}

    class BImpl implements B {}

    List<? extends A> listOfAExtensions;

    void function() {
        B b = new BImpl();
        listOfAExtensions.add(b);
        // error
        // The method add(capture#1-of ? extends Test.A)
        // in the type List<capture#1-of ? extends Test.A>
        // is not applicable for the arguments (Test.B)
    }
}
user118967
  • 4,895
  • 5
  • 33
  • 54

1 Answers1

1
List<? extends A> listOfAExtensions

is not the same as

List<A> listOfAExtensions

because you can assign

List<? extends A> listOfAExtensions = new ArrayList<CImpl>();

where CImpl is an implementation of A unrelated to BImpl. If you could add a BImpl to listOfExtensions after that, you would be adding a BImpl to a list of unrelated CImpl, which would not make sense. Therefore the compiler doesn't allow you to add instances of BImpl to listOfAExtensions.

user118967
  • 4,895
  • 5
  • 33
  • 54
Eran
  • 387,369
  • 54
  • 702
  • 768