为什么这段代码不起作用?具体来说,为什么在 if 语句外部完成的类型转换在其内部不成立。
private SuperType currObj;
public void someMethod(SuperType currObj){
if(currObj instanceof aSubType){
currObj = (aSubType) currObj;
if (true){
currObj.someMethodofaSubtype();
}
}
}
最佳答案
行 currObj = (aSubType) currObj
并没有真正产生任何实际效果。为了调用 someMethodofaSubtype()
,编译器需要知道该对象确实是 aSubType
类型。强制转换并没有真正改变底层对象。进行转换,然后将转换结果存储为 aSubType
类型的新变量就可以解决问题。您可能想要类似的东西:
aSubType subCurrObj = (aSubType) currObj;
subCurrObj.someMethodofaSubtype();
关于java - Java 中关于 if 语句的类型转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5526992/