geo*_*geo 74 java casting interface
有人可以向我解释一下编译器在第一次投射时不会抱怨,但是在第二次投射中是否会抱怨?
interface I1 { }
interface I2 { }
class C1 implements I1 { }
class C2 implements I2 { }
public class Test{
public static void main(){
C1 o1 = new C1();
C2 o2 = new C2();
Integer o3 = new Integer(4);
I2 x = (I2)o1; //compiler does not complain
I2 y = (I2)o3; //compiler complains here !!
}
}
Run Code Online (Sandbox Code Playgroud)
Wil*_*lQu 145
当你施放o1并o3用(I2),你告诉编译器,这个类的对象实际上是其宣称的类型的子类,且该子类实现I2.
该Integer班是最后的,所以o3不可能是一个子类的实例Integer:编译器知道你在说谎.C1但是不是最终的,因此o1 可以是C1该实现的子类型的实例I2.
如果你做了C1最终,编译器也会抱怨:
interface I1 { }
interface I2 { }
final class C1 implements I1 { }
class C2 implements I2 { }
public class Test{
public static void main(){
C1 o1 = new C1();
C2 o2 = new C2();
Integer o3 = new Integer(4);
I2 y = (I2)o3; //compiler complains here !!
I2 x = (I2)o1; //compiler complains too
}
}
Run Code Online (Sandbox Code Playgroud)
Buh*_*ndi 15
根据JLS 5.5.1 - 参考类型转换,规则适用:
如果T是类类型,则为| S | <:| T |,或| T | <:| S |.否则,发生编译时错误.
I2 y = (I2)o3; //compiler complains here !!
在这种情况下,Integer和I2是不相关的任何方式,所以发生编译时间错误.另外,因为Integer是final,Integer和之间没有关系I2.
I2I1由于两者都是标记界面(没有合同),因此可以相关.
至于编译的代码,规则如下:
S是o1和T是I2.
希望这可以帮助.
| 归档时间: |
|
| 查看次数: |
21851 次 |
| 最近记录: |