Java Not InstanceOf

Sheeraz Gul 2023年10月12日
Java Not InstanceOf

InstanceOf 關鍵字檢查引用變數是否包含給定的物件引用型別。它返回布林型別,所以我們也可以否定它們。

本教程演示如何在 Java 中否定 InstanceOf 或使用 Not InstanceOf

在 Java 中使用 Not InstanceOf

instanceof 返回一個布林值,因此否定它將返回 false 值。取反 InstanceOf 與 Java 中的其他取反類似。

例如:

if (!(str instanceof String)) { /* ... */
}

或者:

if (str instanceof String == false) { /* ... */
}

讓我們嘗試一個完整的 Java 示例來展示 Not InstanceOf 在 Java 中的用法。

package delftstack;

class Delftstack_One {}

class Delftstack_Two extends Delftstack_One {}

public class Negate_InstanceOf {
  public static void main(String[] args) {
    Delftstack_Two Demo = new Delftstack_Two();

    // A simple not instanceof using !
    if (!(Demo instanceof Delftstack_Two)) {
      System.out.println("Demo is Not the instance of Delftstack_Two");
    } else {
      System.out.println("Demo is the instance of Delftstack_Two");
    }

    // not instanceof using !
    if (!(Demo instanceof Delftstack_One)) {
      System.out.println("Demo is Not the instance of Delftstack_One");
    } else {
      System.out.println("Demo is the instance of Delftstack_One");
    }

    // instanceof returns true for all ancestors, and the object is the ancestor of all classes in
    // Java

    // not instance using == false
    if ((Demo instanceof Object) == false) {
      System.out.println("Demo is Not the instance of Object");
    } else {
      System.out.println("Demo is the instance of Object");
    }

    System.out.println(Demo instanceof Delftstack_One);
    System.out.println(Demo instanceof Delftstack_Two);
    System.out.println(Demo instanceof Object);
  }
}

上面的程式碼建立了兩個父子類來展示 Not InstanceOf 的用法。我們使用了上述兩種方法。

見輸出:

Demo is the instance of Delftstack_Two
Demo is Not the instance of Delftstack_One
Demo is the instance of Object
false
true
true
作者: Sheeraz Gul
Sheeraz Gul avatar Sheeraz Gul avatar

Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.

LinkedIn Facebook