简体   繁体   English

如何在Java中定义一个接口方法来接受一个类或其任何子类?

[英]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.

相关问题 一种Java方法,只能由其自己的类或其他子类调用 - A Java method that can only be called by its own class or by other subclasses Java中有没有办法交出HashSet <Class> 方法的参数,以便该方法将接受Class子类的HashSets? - Is there a way in Java to hand over HashSet<Class> arguments to a method so that the method will accept HashSets of subclasses of Class? Java有什么办法可以使方法只能由类和子类使用? - Java any way to keep a method usable only by class and subclasses? 使用接受任何类作为参数的方法创建Java接口 - Creating a Java Interface with methods that accept any class as a parameter 如何将Java类转换为其子类之一(SocketAddress和InetSocketAddress) - How to turn Java class into one of its subclasses (SocketAddress and InetSocketAddress) JAVA-在接口中定义方法 - JAVA - define a method in interface 如何使“通用方法声明”接受子类 - How to make "generic method declaration" to accept subclasses Java-如何使用泛型定义接口方法 - Java - How to define interface method with generic 有什么方法可以在Java中的单个类,接口或注释中定义httpheaders? - is there any way to define httpheaders in single class,interface or annotation in java? Java为什么不允许不能访问其超类的任何构造函数的子类? - Why does Java disallow subclasses which cannot access any constructors of its super class?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM