Java 双色铸造

Java 双色铸造,java,interface,casting,Java,Interface,Casting,我对这个(可能)简单的铸造示例有一个棘手的问题。你能帮帮我吗 public class Example1 { interface ParentIf{} interface ChildIf extends ParentIf {} interface OtherIf {} class ParentCl {} class ChildCl extends ParentCl {} class OtherCl {} public static void main(String[] args)

我对这个(可能)简单的铸造示例有一个棘手的问题。你能帮帮我吗

public class Example1 {

interface ParentIf{}
interface ChildIf extends ParentIf {}
interface OtherIf {}

class ParentCl {}
class ChildCl extends ParentCl {}
class OtherCl {}

    public static void main(String[] args) {
        ChildIf cI = null;
        ParentIf pI = null;
        OtherIf oI = null;
        ChildCl cC = null;
        ParentCl pC = null;
        OtherCl oC = null;

        cI = (ChildIf)oI; //case1 - fine

        cC = (ChildCl)oC; //case2 - inconvertible types

        cI = (ChildIf)oC; //case3 - fine
    }
}
但更尴尬的是,我不知道为什么其他两种说法是好的

我看不出OtherIf和ChildIf之间有任何联系。那么,在案例1中,当这两个接口之间没有“扩展”时,如何将OtherIf强制转换为ChildIf呢

cI = (ChildIf)oI;
很好,因为
oI
可以是同时实现ChildIf和OtherIf的类的实例

cI = (ChildIf)oC;

这很好,因为
oC
可能是扩展
OtherClass
anec实现
ChildIf

的类的实例,我仍然有点困惑。“可能”意味着目前oI不是实现ChildIf和OtherIf的类的实例,但IntelliJ“知道”它可能是?抱歉,我看不到:/oI是一个变量,它引用类型为
OtherIf
的对象。编译器不关心运行时对象的具体类型。它关心变量的声明类型:OtherIf。类型是否可以同时实现ChildIf和OtherIf?是的,有可能。所以演员阵容可能会成功,这是有道理的。