Suppose I have a class called Animal and an interface called AnimalTrainer.
public interface AnimalTrainer
{
void trainAnimal(Animal animal);
}
Now, the problem arises when I want to write an implementation that trains only Lion, for example, where Lion extends Animal.
public class LionTrainer implements AnimalTrainer
{
public void trainAnimal(Lion lion)
{
// code
}
}
But this doesn't work. How can I define the trainAnimal method in AnimalTrainer such that the above LionTrainer implementation is possible? Or would I have to change the LionTrainer implementation?
You need to type AnimalTrainer
public interface AnimalTrainer<T extends Animal>
{
public void trainAnimal(T animal);
}
public class LionTrainer implements AnimalTrainer<Lion>
{
public void trainAnimal(Lion lion);
}