1

I was reading about Java Generics and following part seemed problematic:

public class Farm {
  private List<Animal> animals;

  public void addAnimals(Collection<Animal> newAnimals) {
    animals.addAll(newAnimals);
  }
}

farm.addAnimals(cats); // Compilation error
farm.addAnimals(dogs); // Compilation error

Cat and Dog are subclasses of Animal.

In order to make it work it is required to define a wildcard type with an upper bound:

public void addAnimals(Collection<? extends Animal> newAnimals)

Shouldn't I be able to use subclasses and superclasses interchangeably without needing to set an upper bound according to the definition of Liskov substition:

Substitutability is a principle in object-oriented programming stating that an object (such as a class) and a sub-object (such as a class that extends the first class) must be interchangeable without breaking the program.

acanbiler
  • 153
  • 1
  • 8
  • Generics are not covariant. Hence, a `Collection` is not a `Collection`. This does not break LSP, since LSP is not concerned with generics. We use [the PECS mnoemonic](https://stackoverflow.com/questions/2723397/what-is-pecs-producer-extends-consumer-super). – Turing85 Dec 22 '21 at 19:02
  • `List`, `List`, `Collection`, `Collection` etc are not subclasses of `Collection`. – Sweeper Dec 22 '21 at 19:02
  • Just in case this wasn't clear, note that the types that we are substituting are not `Cat`s, `Dog`s and `Animal`s, but _collections_ of those things. – Sweeper Dec 22 '21 at 19:08
  • @Sweeper makes perfect sense, thanks. I'll look into PECS. – acanbiler Dec 22 '21 at 19:15
  • Well, the [accepted and most upvoted answer](https://stackoverflow.com/a/2745301/507738) from the duplicate link nicely explains *why* it is a good thing that the compiler disallows such things. – MC Emperor Dec 22 '21 at 20:20

1 Answers1

3

A collection of only cats is not a subclass of a collection of any animal.

This and the compilation error are good things. Otherwise, you could declare a collection of only cats, and stick a dog in it. Trouble would ensue.

Andy Thomas
  • 84,978
  • 11
  • 107
  • 151