我很困惑。
假设我们有以下类(class):
class Shape { /* ... */ }
class Square extends Shape { /* ... */ }
生成的 boolean 值是什么,为什么会这样?
Shape shape = ...;
boolean b1 = shape instanceof Square;
Square square = ...;
boolean b2 = ((Shape) square) instanceof Square;
boolean b3 = shape instanceof Object;
据我所知,子类是父类的实例,但反之则不然?
最佳答案
在此代码中:
Number n = new Integer(42);
Number
是 n
的表观类型,而 Integer
是其真实类型 em>.
强制转换会更改表观类型,而instanceof
会检查真实类型。
因此,转换对 instanceof
结果没有影响。
关于java - 强制转换会影响instanceof操作的结果吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41892132/