java - enthuware OCAJP 实例

标签 java instanceof scjp

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运算符(binstanceof Bird)的计算结果不为false,而是给我一个编译时错误。 附: -我无法理解 Enthuware 试图向我解释的内容

我得到的编译时错误是

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

if(b instanceof Bird) System.out.println("f 是一只鸟"); ^

必需:鸟

发现: bat

1 个错误

最佳答案

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

关于java - enthuware OCAJP 实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18811636/

相关文章:

java - 如何在Java中获取类的TypeTag

java - 如何确保集合仅包含接口(interface)的每个实现之一

java - 是否可以覆盖 DateFormat.getDateTimeInstance()?

java - 有人能解释一下这个关于枚举的程序在java中是如何工作的吗?

java - 根据构造函数参数实例化特定的子类型

java - 声明泛型类型时的编译器警告

java - 输入不匹配异常错误

java - 我可以制作多少个线程有限制吗

java - 如何使用 spring saml 应用程序的公钥和私钥创建 JKS 文件?

java - java中如何实现模式匹配,避免instanceof?