【问题标题】:instanceof operator in java with interfaces [duplicate]java中带有接口的instanceof运算符[重复]
【发布时间】:2017-08-10 09:24:26
【问题描述】:

任何人都可以使用 instanceof 运算符解释 Java 中的以下行为吗?

Runnable r = new Thread();

尽管变量 r 的类型是 Runnable 并且 instanceof 比较是在不在同一类层次结构中的类上完成的

System.out.println(r instanceof String); // This line does not compile 

System.out.println(r instanceof Vector); // This line compiles

System.out.println(r instanceof FileNotFoundException); // This line compiles

【问题讨论】:

    标签: java polymorphism instanceof


    【解决方案1】:

    String 类是 final - 这意味着它不能被子类化。此外,它没有实现Runnable。所有这些在编译时都是已知的;因此,编译错误。

    【讨论】:

    • 更重要的是:String 没有实现 Runnable,并且它不能有 子类 来实现(因为它是 final)。跨度>
    • @T.J.Crowder 是的 +1 这会很好地编辑到答案中以使其更有用
    • @ErwinBolwidt:是的。我把它留给莫里斯。但无论如何,整件事都是骗人的,所以......
    【解决方案2】:

    一个例子:

    static class First {
    
    }
    
    static final class Second {
    
    }
    

    比:

        Runnable r = new Thread();
    
        System.out.println(r instanceof First);
    
        System.out.println(r instanceof Second);
    

    编译器看到Secondfinal,所以它不能有任何sub-classes,所以它不能实现Runnable

    【讨论】:

      【解决方案3】:

      String 类是final,它没有实现Runnable 接口。因此,r instanceof String 永远不会返回 true(因为不可能有任何 String 的子类可以实现 Runnable),这就是编译器不允许它的原因。

      另一方面,Vector 类或FileNotFoundException 类的子类可能实现了Runnable 接口,因此r instanceof Vectorr instanceof FileNotFoundException 可能在编译器中返回true可以说。

      这被JLS 15.20.2覆盖:

      如果将 RelationalExpression 转换为 ReferenceType(第 15.16 节)作为编译时错误被拒绝,则 instanceof 关系表达式同样会产生编译时错误。 在这种情况下,instanceof 表达式的结果永远不会为真

      【讨论】:

        猜你喜欢
        • 2016-07-31
        • 1970-01-01
        • 2012-07-29
        • 2023-02-02
        • 1970-01-01
        • 1970-01-01
        • 2015-10-02
        • 1970-01-01
        • 2012-07-24
        相关资源
        最近更新 更多