Java instanceof运算符的行为不一致
我收到了带有两个接口的Java代码Java instanceof运算符的行为不一致,java,oop,inheritance,virtual-machine,instanceof,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&g
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>
}
然而,在我的本地机器上,它确实像预期的那样坏了
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
应该在哪里起作用的场景?ParentClass myVariable=new ChildClass()
是有效的,并且是通过测试的一个例子。因此,有必要知道您在放置
的地方究竟写了什么。但是您是对的,给定相同的代码,它在所有JRE上的作用应该是相同的;条件将为true,因为您用“!”来否定它(false)。不管怎样,结果在所有JVM上都应该是一样的。@geert3我认为他不想分配新的ChildClass()。。。但我可能错了。。见我的评论before@progressive_overload在这种情况下,条件确实为真,因此程序将抛出异常,这是预期的行为。问题是,如果,为什么它会跳过(也就是说,为什么在某些情况下整个条件都是错误的)。@tak3shi我对远程机器(工作的机器)的访问权限有限,所以我没有尝试玩具代码。不过,我今天晚些时候可以试试。ParentClass myVariable=new ChildClass()
是有效的,这将是一个通过测试的示例。因此,有必要知道您在放置
的地方究竟写了什么。但是您是对的,给定相同的代码,它在所有JRE上的作用应该是相同的;条件将为true,因为您用“!”来否定它(false)。不管怎样,结果在所有JVM上都应该是一样的。@geert3我认为他不想分配新的ChildClass()。。。但我可能错了。。见我的评论before@progressive_overload在这种情况下,条件确实为真,因此程序将抛出异常,这是预期的行为。问题是,如果
,为什么它会跳过(也就是说,为什么在某些情况下整个条件都是错误的)。@tak3shi我对远程机器(工作的机器)的访问权限有限,所以我没有尝试玩具代码。不过我今天晚些时候可以试试。
myVariable instanceof ParentClass -> true
myVariable instanceof ISuper -> true
myVariable instanceof ChildClass -> false
myVariable instanceof ISub -> false