With a single layer of inheritance I can do something like this:
// Dog extends Animal
List<Dog> dogs = ...;
// Cat extends Animal
List<Cat> cats = ...;
List<? extends Animal> animals = new ArrayList<>();
animals.addAll(cats);
animals.addAll(dogs);
I can do this without casting, which is nice.
But what if I have a scenario like the following?
// Plant extends LivingBeing
List<Plant> plants = ...;
// Animal extends LivingBeing
// Cat extends Animal
List<Cat> cats = ...;
List<? extends LivingBeing> livingThings = new ArrayList<>();
// This is fine
lvingThings.addAll(plants);
// FIXME: Fails because Cat doesn't directly extend LivingBeing
livingThings.addAll(cats);
Is there a way to specify an upper bound that is not a direct parent of all members of the list, so that I can avoid casting?