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

问题描述

interface Printable {}
class BlackInk {}

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

如果编译并运行前面的代码,结果是 printable = (Printable)b​​lackInk; 处的 ClassCastException.但是,如果将 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.

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

05-18 03:19