How to use the instanceOf keyword in Java?

The instanceof keyword is used to check if an object belongs to a certain class or its subclass. The syntax for using it is as follows:

object instanceof className

Here, the object is the item to be inspected, and className is the name of the class to be examined.

Example code:

class Animal {
    // 父类 Animal
}

class Dog extends Animal {
    // 子类 Dog
}

public class Main {
    public static void main(String[] args) {
        Animal animal = new Animal();
        Dog dog = new Dog();
        
        // 检查 animal 是否是 Animal 类的实例
        boolean isAnimal = animal instanceof Animal; // true
        
        // 检查 dog 是否是 Animal 类的实例
        boolean isDogAnimal = dog instanceof Animal; // true
        
        // 检查 dog 是否是 Dog 类的实例
        boolean isDog = dog instanceof Dog; // true
        
        // 检查 animal 是否是 Dog 类的实例
        boolean isAnimalDog = animal instanceof Dog; // false
    }
}

In the example code above, we checked whether the objects ‘animal’ and ‘dog’ are instances of the class ‘Animal’ or its subclasses. Based on the results, we can see that the ‘animal’ object is an instance of the ‘Animal’ class, while the ‘dog’ object is an instance of both the ‘Animal’ class and the ‘Dog’ class.

bannerAds