铸造会影响instanceof操作的结果吗?

use*_*225 2 java object instanceof

我糊涂了.

假设我们有以下课程:

class Shape { /* ... */ }
class Square extends Shape { /* ... */ }
Run Code Online (Sandbox Code Playgroud)

什么是由此产生的布尔值,为什么会这样呢?

Shape shape = ...;
boolean b1 = shape instanceof Square;

Square square = ...;
boolean b2 = ((Shape) square) instanceof Square;

boolean b3 = shape instanceof Object;
Run Code Online (Sandbox Code Playgroud)

据我所知,子类是父类的实例,但不是相反?

rom*_*m1v 7

在这段代码中:

Number n = new Integer(42);
Run Code Online (Sandbox Code Playgroud)

Number显而易见的类型n,而Integer是其真实类型.

强制转换会改变表观类型,同时instanceof检查实际类型.

因此,铸造对instanceof结果没有影响.