答案 0 :(得分:1)
规则是,如果将接口类型的引用强制转换为任何其他类型,编译器将盲目地信任您。
在运行时期间,如果引用指向您正在将其转换为所有类型的对象的引用将顺利进行,否则将引发ClassCastException
。
例如,假设你有:
class FoodProcessor implements CoffeeExpress, Blender, Juicer{....}
然后:
Object o = new FoodProcessor();
CoffeeExpress c = (CoffeeExpress)o;//fine
Blender b = (Blender)o;//fine
Juicer j = (Juicer)o;//fine
FoodProcessor f = (FoodProcessor)o;//fine
A a = new A();//where A does not implement any of CoffeeExpress, Blender and Juicer and does not derive from FoodProcessor
c = (CoffeeExpress)a;//ClassCastException
b = (Blender)a;//ClassCastException
j = (Juicer)a;//ClassCastException
f = (FoodProcessor)a;//ClassCastException
要回答您的问题,您必须问自己:getSomeIFile();
是否返回File
类型的值或源自File
的值?