Java instanceof 运算符

Java 中的 instanceof 运算符用于检查一个对象是否是某个特定类或接口的实例。

其语法为

objectName instanceOf className;

如果 objectNameclassName 的实例,则该运算符返回 true。否则,它返回 false


示例:Java instanceof

class Main {

  public static void main(String[] args) {

    // create a variable of string type
    String name = "Programiz";
    
    // checks if name is instance of String
    boolean result1 = name instanceof String;
    System.out.println("name is an instance of String: " + result1);

    // create an object of Main
    Main obj = new Main();

    // checks if obj is an instance of Main
    boolean result2 = obj instanceof Main;
    System.out.println("obj is an instance of Main: " + result2);
  }
}

输出

name is an instance of String: true
obj is an instance of Main: true

在上面的示例中,我们创建了一个 String 类型的变量 name 和一个 Main 类的对象 obj

在这里,我们使用 instanceof 运算符分别检查 nameobj 是否是 String 类和 Main 类的实例。在这两种情况下,运算符都返回 true

注意:在 Java 中,String 是一个类,而不是一个原始数据类型。要了解更多信息,请访问Java String


Java instanceof 在继承中的使用

我们可以使用 instanceof 运算符来检查子类的对象是否也是超类的实例。例如,

// Java Program to check if an object of the subclass
// is also an instance of the superclass

// superclass
class Animal {
}

// subclass
class Dog extends Animal {
}

class Main {
  public static void main(String[] args) {

    // create an object of the subclass
    Dog d1 = new Dog();

    // checks if d1 is an instance of the subclass
    System.out.println(d1 instanceof Dog);        // prints true

    // checks if d1 is an instance of the superclass
    System.out.println(d1 instanceof Animal);     // prints true
  }
}

在上面的示例中,我们创建了一个继承自超类 Animal 的子类 Dog。我们创建了 Dog 类的一个对象 d1

在打印语句中,请注意表达式:

d1 instanceof Animal

在这里,我们使用 instanceof 运算符来检查 d1 是否也是超类 Animal 的实例。


Java instanceof 在接口中的使用

instanceof 运算符也用于检查类的对象是否也是该类实现的接口的实例。例如,

// Java program to check if an object of a class is also
//  an instance of the interface implemented by the class

interface Animal {
}

class Dog implements Animal {
}

class Main {
  public static void main(String[] args) {

    // create an object of the Dog class
    Dog d1 = new Dog();

    // checks if the object of Dog
    // is also an instance of Animal
    System.out.println(d1 instanceof Animal);  // returns true
  }
}

在上面的示例中,Dog 类实现了 Animal 接口。在打印语句中,请注意表达式:

d1 instanceof Animal

这里,d1Dog 类的实例。instanceof 运算符检查 d1 是否也是接口 Animal 的实例。

注意:在 Java 中,所有类都继承自 Object 类。因此,所有类的实例也是 Object 类的实例。

在前面的示例中,如果我们检查:

d1 instanceof Object

结果将是 true


另请阅读

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战