interface Printable {}
class BlackInk {}
public class Main {
public static void main(String args[]) {
Printable printable = null;
BlackInk blackInk = new BlackInk();
printable = (Printable)blackInk;
}
}
Run Code Online (Sandbox Code Playgroud)
如果编译并运行上述代码,则结果为ClassCastException printable = (Printable)blackInk;.但是,如果将Printable更改为类,则不会编译,因为blackInk无法强制转换为Printable.当Printable是一个接口时,为什么要编译?
interface I {
}
class A {
}
class B {
}
public class Test {
public static void main(String args[]) {
A a = null;
B b = (B)a; // error: inconvertible types
I i = null;
B b1 = (B)i;
}
}
Run Code Online (Sandbox Code Playgroud)
我知道为什么a不能被施展B,因为B不是从继承A.
我的问题是,为什么B b1 = (B)i;允许,因为B不是实现I?
为什么B b1 = (B)i;这一行不会强制运行时异常,因为它i是null?
在下面的代码中,x的类型是I(虽然x也实现了J但在编译时不知道),为什么(1)处的代码不会导致编译时错误.因为在编译时只考虑引用的类型.
public class MyClass {
public static void main(String[] args) {
I x = new D();
if (x instanceof J) //(1)
System.out.println("J");
}
}
interface I {}
interface J {}
class C implements I {}
class D extends C implements J {}
Run Code Online (Sandbox Code Playgroud)