【问题标题】:Interfaces casting dilema [duplicate]接口铸造困境[重复]
【发布时间】:2017-11-14 16:58:44
【问题描述】:

我对这个(可能)简单的转换示例有一个尴尬的问题。你能帮帮我吗?

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 之间的任何联系。那么在case1中这两个接口之间没有“扩展”时,如何将OtherIf转换为ChildIf?

【问题讨论】:

    标签: java interface casting


    【解决方案1】:
    cI = (ChildIf)oI;
    

    很好,因为oI 可以是实现 ChildIf 和 OtherIf 的类的实例。

    cI = (ChildIf)oC;
    

    很好,因为oC 可以是扩展OtherClass anec 实现ChildIf 的类的实例。

    【讨论】:

    • 我还是有点困惑。 “可能”意味着此时 oI 不是实现 ChildIf 和 OtherIf 的类的实例,但 IntelliJ“知道”它可能是?对不起,我看不到它:/
    • oI 是一个变量,它引用OtherIf 类型的对象。编译器不关心运行时对象的具体类型。它关心变量的声明类型:OtherIf。一个类型是否可以同时实现 ChildIf 和 OtherIf?是的,这是可能的。所以演员阵容可能会成功,所以这是有道理的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-13
    • 1970-01-01
    • 1970-01-01
    • 2015-01-03
    相关资源
    最近更新 更多