[英]How to define an interface method to accept a class or any of its subclasses in Java?
Suppose I have a class called Animal and an interface called AnimalTrainer. 假设我有一个名为Animal的类和一个名为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. 现在,当我想编写仅训练Lion的实现时(例如,Lion扩展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?
如何在AnimalTrainer中定义trainAnimal方法,以使上述LionTrainer实现成为可能? Or would I have to change the LionTrainer implementation?
还是我必须更改LionTrainer的实现?
You need to type AnimalTrainer 您需要输入AnimalTrainer
public interface AnimalTrainer<T extends Animal>
{
public void trainAnimal(T animal);
}
public class LionTrainer implements AnimalTrainer<Lion>
{
public void trainAnimal(Lion lion);
}
Use generics: 使用泛型:
public interface AnimalTrainer<T extends Animal> {
void trainAnimal(T animal);
}
class LionTrainer implements AnimalTrainer<Lion> {
public void trainAnimal(Lion lion) {...}
}
You should use generic types... 您应该使用通用类型...
public interface AnimalTrainer<T extends Animal>
{
public void trainAnimal(T animal);
}
then LionTrainer implements AnimalTrainer<Lion>
... 然后
LionTrainer implements AnimalTrainer<Lion>
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.