How to use the instanceOf keyword in Java.

The “instanceOf” keyword is used to determine if an object is an instance of a specific class or one of its subclasses. It is used in the following way:

// 定义一个Animal类
class Animal {}

// 定义一个Dog类,继承自Animal类
class Dog extends Animal {}

public class Main {
    public static void main(String[] args) {
        // 创建一个Animal对象
        Animal animal = new Animal();
        
        // 创建一个Dog对象
        Dog dog = new Dog();
        
        // 使用instanceOf关键字检查对象类型
        if (animal instanceof Animal) {
            System.out.println("animal is an instance of Animal");
        }
        
        if (dog instanceof Dog) {
            System.out.println("dog is an instance of Dog");
        }
        
        // 还可以检查对象是否是父类或接口的实例
        if (dog instanceof Animal) {
            System.out.println("dog is an instance of Animal");
        }
        
        // 如果对象为null,instanceOf判断会返回false
        Animal nullAnimal = null;
        if (nullAnimal instanceof Animal) {
            System.out.println("nullAnimal is an instance of Animal");
        } else {
            System.out.println("nullAnimal is not an instance of Animal");
        }
    }
}

In the example above, we used the instanceOf keyword to check the types of the animal and dog objects, as well as whether the dog object is a subclass of Animal. We also demonstrated that when an object is null, the instanceOf check returns false.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds