相关疑难解决方法(0)

为什么在转换为不相关的接口时会编译?

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是一个接口时,为什么要编译?

java interface classcastexception

8
推荐指数
2
解决办法
1219
查看次数

解释这个关于对象引用转换的输出?

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?

java casting interface

7
推荐指数
1
解决办法
168
查看次数

为什么这个instanceof代码工作并且不会导致编译时错误?

在下面的代码中,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)

java instanceof

6
推荐指数
1
解决办法
4059
查看次数