This might sound a little bit trivial, but I'm really not able to find the crux of the matter.
List<Dog> dogs = getListOfDogs();
List<Cat> cats = getListOfCats();
feed(dogs);
feed(cats);
public void feed(List<Animal> animals) {
// feed the animal:
// depending on the type of animal, I might want to give it
// different kind of food.
}
class Dog implements Animal { /**/ }
class Cat implements Animal { /**/ }
interface Animal { /**/ }
I'm in a context very similar to the one depicted above.
Let's also suppose that getListOfDogs
and getListOfCats
are fixed, and there's no way to act on that side.
Of course, as put in that way, it's an illegal code: feed
accepts only List<Animal>
types, while I can only have List<Cat>
and List<Dog>
.
Since feed
is a function that is almost identical for the two animals, with the exception of the kind of food (and I can manage it via instanceof
), I would like to avoid copying it, just changing the signatures.
Is there any way to super-cast the two lists? Something like this (that is obviously incorrect): feed((List<Animal>) getListOfDogs());