java接口转换,接口中的Java转换

Can someone please explain to me how the compiler does not complain in the first casting, but does complain in the second?

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 !!

}

}

解决方案

When you cast o1 and o3 with (I2), you tell the compiler that the class of the object is actually a subclass of its declared type, and that this subclass implements I2.

The Integer class is final, so o3 cannot be an instance of a subclass of Integer: the compiler knows that you're lying. C1 however is not final, so o1 could be an instance of a subtype of C1 that implements I2.

If you make C1 final, the compiler will complain too:

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

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值