[英]Object universal superclass java instanceof
Can someone provide an explanation for when (x instancef Object)
will not equal true? 有人可以提供有关何时
(x instancef Object)
不等于true的解释吗? Here's the full question? 这是完整的问题吗?
Object
is the universal superclass in Java, a superclass of all other classes.Object
是Java中的通用超类,它是所有其他类的超类。 However, the expressionx instanceof Object
does not always equal true.但是,表达式
x instanceof Object
并不总是等于true。 Devise a declaration forx
to demonstrate this?为
x
设计一个声明来证明这一点?
null
is not an instance of any class, and therefore returns false
to the use of the instanceof
operator: null
不是任何类的实例,因此使用instanceof
运算符返回false
:
Object x = null;
if (!x instanceof Object) {
System.out.println ("we get here since X is null");
}
Clearly the null
answer is the "correct one". 显然,
null
答案是“正确答案”。 But here is a pedantic alternative: 但是,这里有一个古怪的选择:
public class Test {
private class Object {}
public static void main(String[] args) {
java.lang.Object s = new String("foo");
System.out.println((s instanceof Object));
}
}
Prints 打印
false
Here we abuse that fact that Object
does not always refer to java.lang.Object
. 在这里,我们滥用
Object
不总是引用java.lang.Object
事实。
如果x
为null
, instanceof
将返回false
。
Duplicate of When is “obj instanceof Object” false in Java? Java中“ obj instanceof Object”何时为假?
If Object a=null;
如果
Object a=null;
then a instanceof Object
returns false
然后
a instanceof Object
返回false
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.