我提前为标题道歉。
我正在尝试将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 {
...
}
Groom
可以像这样通用:
interface Groom<T extends Animal> {
void groom(T t);
}
public class CatGroomer implements Groom<Cat> {
void groom(Cat animal) {
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句