1
interface Flyer{ }  
class Bird implements Flyer { }  
class Eagle extends Bird { }  
class Bat { }  

public class TestClass {  

public static void main(String[] args) {  
    Flyer f = new Eagle();  
    Eagle e = new Eagle();  
    Bat b = new Bat();  

    if(f instanceof Flyer) System.out.println("f is a Flyer");  
    if(e instanceof Bird) System.out.println("e is a Bird");  
    if(b instanceof Bird) System.out.println("f is a Bird");  
    }  
}  

这是来自 Enthuware 的代码示例。我无法弄清楚为什么第三个 instanceof 运算符( b instanceof Bird )不会评估为 false 而是给我一个编译时错误。PS -我无法理解 Enthuware 试图向我解释的内容

我得到的编译时错误是

TestClass.java:16:错误:不可转换的类型

if(b instanceof Bird) System.out.println("f is a Bird"); ^

要求:鸟

发现:蝙蝠

1 个错误

4

2 回答 2

2

仅当对象通过某种继承链接时,instanceof 运算符才评估 true 或 false,否则抛出错误

于 2013-09-15T14:17:47.437 回答
0

第三个条件给出了编译时错误,因为 Bat 没有扩展到 Bird 并且作为 Java 类最多可以扩展一个类的第二个原因,Bat 的子类不可能扩展到 Bird 类并且基于这条规则 JVM 足够聪明,可以判断出蝙蝠不可能是鸟。

于 2016-09-22T02:26:22.737 回答