假设我们有以下代码块:
if (thing instanceof ObjectType) {
((ObjectType)thing).operation1();
((ObjectType)thing).operation2();
((ObjectType)thing).operation3();
}
所有类型转换使得代码看起来很难看,有没有办法在该代码块中声明’thing’作为ObjectType?我知道我能做到
OjectType differentThing = (ObjectType)thing;
从那时起开始使用’differentThing’,但这会给代码带来一些困惑.有没有更好的方法来做到这一点,可能是这样的
if (thing instanceof ObjectType) {
(ObjectType)thing; //this would declare 'thing' to be an instance of ObjectType
thing.operation1();
thing.operation2();
thing.operation3();
}
我很确定过去曾问过这个问题,但我找不到它.请随意指出可能重复的内容.