简体   繁体   English

对象通用超类Java instanceof

[英]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 expression x instanceof Object does not always equal true. 但是,表达式x instanceof Object并不总是等于true。 Devise a declaration for x 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事实。

如果xnullinstanceof将返回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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM