传递对象的实现而无需强制转换

时间:2018-11-26 14:21:50

标签: java interface downcast

我为标题提前表示歉意。

我试图将实现Cat的对象Animal传递给名为Groom的接口。在处理Groom实现的修饰的Cat中,由于Groom接口接受Animal作为参数,我不得不向下转换对象以了解修饰的内容。 / p>

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

1 个答案:

答案 0 :(得分:3)

Groom可以这样通用:

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

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

  }
}