接口中的Java转换 [英] Java casting in interfaces

查看:92
本文介绍了接口中的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 !!
     }
}

推荐答案

使用(I2)转换o1o3时,您告诉编译器该对象的类实际上是其声明类型的子类. ,并且该子类实现了I2.

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.

Integer类是 final ,因此o3不能是Integer子类的实例:编译器知道您在说谎. C1并不是最终的,因此o1 可以是实现I2C1子类型的实例.

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.

如果将C1定为最终版本,编译器也会抱怨:

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

这篇关于接口中的Java转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆