java - 传递对象的实现而不进行强制转换
问题描述
我提前为标题道歉。
我正在尝试将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) {
}
}
推荐阅读
- python - Else 是无效的语法
- amazon-web-services - 使用带有多个资源的 tag_secifications 设置启动模板
- django - Django + Celery + Flower 似乎打破了 RabbitMQ 代理
- c# - 仅在特定条件下显示方法
- javascript - 如何在javascript中将func1响应值传递给func2
- ios - 我的调试区域中的错误域 = NSCocoaErrorDomain 代码 = 4099
- c++ - 全局变量在下一个循环之前不更新
- c++ - 用观察者模式(C++)中的更新请求问题淹没视图
- r - 在 R pROC 中存储多个 AUC 和 CI
- swift - 如何将字典的值约束到协议