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/