Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

java中instanceof

作者:愛火焚城   发布日期:2025-05-22   浏览:52

// 定义一个父类 Animal
class Animal {
    public void makeSound() {
        System.out.println("Some generic animal sound");
    }
}

// 定义一个子类 Dog,继承自 Animal
class Dog extends Animal {
    @Override
    public void makeSound() {
        System.out.println("Bark");
    }
}

public class InstanceofExample {
    public static void main(String[] args) {
        Animal myAnimal = new Animal();
        Animal myDog = new Dog();

        // 使用 instanceof 检查对象是否是某个类的实例
        if (myAnimal instanceof Dog) {
            System.out.println("myAnimal is a Dog");
        } else {
            System.out.println("myAnimal is not a Dog");
        }

        if (myDog instanceof Dog) {
            System.out.println("myDog is a Dog");
        } else {
            System.out.println("myDog is not a Dog");
        }

        // instanceof 也可以用于检查对象是否为某个类或其子类的实例
        if (myDog instanceof Animal) {
            System.out.println("myDog is an Animal or its subclass");
        }

        // 自 Java 16 起,instanceof 支持模式匹配
        if (myDog instanceof Dog dog) {
            dog.makeSound(); // 直接使用变量 dog
        }
    }
}

解释说明:

  • instanceof 关键字用于检查对象是否是指定类型或其子类型的实例。
  • 在代码中,我们定义了一个父类 Animal 和一个子类 Dog
  • 我们创建了两个对象:myAnimalAnimal 类的实例,而 myDogDog 类的实例。
  • 使用 instanceof 检查 myAnimalmyDog 是否是 Dog 类的实例,并输出相应的结果。
  • 自 Java 16 起,instanceof 支持模式匹配,可以在条件语句中直接声明并使用变量(如 if (myDog instanceof Dog dog))。

上一篇:java远程debug

下一篇:java树形结构递归实现

大家都在看

java连接数据库的代码

ubuntu 卸载java

java sort用法

java collections.sort

java file类的方法

java 判断

java时间数据类型

java 时间加一天

java demo

java 截取

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站