首页 > 解决方案 > 传递对象的实现而不进行强制转换

问题描述

我提前为标题道歉。

我正在尝试将Cat实现的对象传递Animal给名为Groom. 在我Groom处理Cat实现的修饰中,我必须向下转换我的对象以了解我正在修饰的内容,因为Groom接口接受Animal作为参数。

public interface Groom {
    void groom(Animal animal);
}

public class CatGroomer implements Groom {
    void groom(Animal animal) {
        Cat cat = (Cat) animal; // <---- how can i avoid this downcast
    }
}

public interface Animal {
    void do();
    void animal();
    void things();
}

public class Cat implements Animal {
    ...
}

标签: javainterfacedowncast

解决方案


Groom可以像这样通用:

interface Groom<T extends Animal> {
  void groom(T t);
}

public class CatGroomer implements Groom<Cat> {
  void groom(Cat animal) {

  }
}

推荐阅读