instanceof运算符的行为不一致

时间:2016-05-11 14:02:41

标签: java oop inheritance virtual-machine instanceof

我已经将Java代码交给了两个接口

interface ISuper {}
interface ISub extends ISuper {}

和两个实现它们的类

class ParentClass implements ISuper {}
class ChildClass extends ParentClass implements ISub {}

在代码中

ParentClass myVariable = <properly defined ParentClass object>

if(! (myVariable instanceof ISub)) {
    <throw an error that breaks the code>
}

仅仅是阅读此内容,似乎检查(myVariable instanceof ISub)应始终返回false,因为ParentClass未实现ISub,因此代码应始终中断。因此,似乎作者希望将myVariable 识别为ISub的实例。

事实上,这些代码在某些机器上确实可以正常执行!特别是,它无法在

下运行的代码中断
java version "1.7.0_101"
OpenJDK Runtime Environment (IcedTea 2.6.6) (7u101-2.6.6-0ubuntu0.14.04.1) 
OpenJDK 64-Bit Server VM (build 24.95-b01, mixed mode)

但是,它确实在我的本地计算机上按预期中断了

java version "1.8.0_60"
Java(TM) SE Runtime Environment (build 1.8.0_60-b27)
Java HotSpot(TM) 64-Bit Server VM (build 25.60-b23, mixed mode)

我用一些玩具代码进行了一些本地测试并找到了

myVariable instanceof ParentClass  ->  true
myVariable instanceof ISuper       ->  true
myVariable instanceof ChildClass   ->  false
myVariable instanceof ISub         ->  false

一切如预期。

任何人都可以推断原作者的意图吗?是否存在我不知道instanceof的使用应该在何处起作用的场景?

0 个答案:

没有答案
相关问题