为什么在转换为不相关的接口时会编译? [英] Why does it compile when casting to an unrelated interface?

查看:94
本文介绍了为什么在转换为不相关的接口时会编译?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

interface Printable {}
class BlackInk {}

public class Main {
    public static void main(String args[]) {
        Printable printable = null;
        BlackInk blackInk = new BlackInk();
        printable = (Printable)blackInk;
    }
}

如果编译并运行上述代码,结果是的一个ClassCastException打印=(可打印)blackInk; 。但是,如果将Printable更改为类,则不会编译,因为blackInk无法强制转换为Printable。当Printable是一个接口时为什么要编译?

If the preceding code is compiled and run, the result is a ClassCastException at printable = (Printable)blackInk;. But, if Printable is changed to a class, it doesn't compile because blackInk can't be cast to Printable. Why does it compile when Printable is an interface?

推荐答案

编译器不知道这不起作用:你可能有实现Printable的BlackInk的子类。然后演员阵容很好。

The compiler does not know that this won't work: You could have a subclass of BlackInk that implements Printable. Then the cast would be fine.

在编译器知道它不起作用的情况下,你会收到错误。

In situations where the compiler knows it won't work, you will get an error.

例如,如果你使BlackInk final (这样就没有子类)就会出错。

For example, if you make BlackInk final (so that there can be no subclasses) you get an error.

这篇关于为什么在转换为不相关的接口时会编译?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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