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中的代码示例。我不明白为什么操作符的第三个实例(B instanceof Bird)不计算为false,而是给我一个编译时错误。P.S. -i无法理解恩图瓦试图解释我的事情
我得到的编译时错误是
TestClass.java:16:错误:不可转换类型
如果(B) System.out.println("f是鸟“);^
所需:鸟
发现:蝙蝠
1个错误
发布于 2013-09-15 14:17:47
仅当对象通过某种继承链接并抛出错误时,instanceof运算符才计算true或false。
发布于 2016-09-22 02:26:22
第三个条件给出了编译时错误,因为Bat没有扩展到Bird,而Java类最多只能扩展一个类的第二个原因是,Bat的子类不可能扩展到Bird类,并且基于这个规则,JVM足够聪明地发现Bat不能是鸟。
https://stackoverflow.com/questions/18811636
复制相似问题