Java中instanceOf關(guān)鍵字怎么用

小億
85
2024-03-04 15:49:18

instanceOf關(guān)鍵字用于檢查一個(gè)對(duì)象是否是某個(gè)特定類的實(shí)例,或者是否是其子類的實(shí)例。具體用法如下:

// 定義一個(gè)Animal類
class Animal {}

// 定義一個(gè)Dog類,繼承自Animal類
class Dog extends Animal {}

public class Main {
    public static void main(String[] args) {
        // 創(chuàng)建一個(gè)Animal對(duì)象
        Animal animal = new Animal();
        
        // 創(chuàng)建一個(gè)Dog對(duì)象
        Dog dog = new Dog();
        
        // 使用instanceOf關(guān)鍵字檢查對(duì)象類型
        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");
        }
        
        // 還可以檢查對(duì)象是否是父類或接口的實(shí)例
        if (dog instanceof Animal) {
            System.out.println("dog is an instance of Animal");
        }
        
        // 如果對(duì)象為null,instanceOf判斷會(huì)返回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");
        }
    }
}

在上面的示例中,我們使用instanceOf關(guān)鍵字分別檢查了animal和dog對(duì)象的類型,以及dog對(duì)象是否是Animal的子類。最后還演示了當(dāng)對(duì)象為null時(shí),instanceOf判斷返回false的情況。

0