简体   繁体   中英

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.

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);
 }

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> ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM