instanceof的使用

发布时间 2023-03-28 23:01:34作者: 盗版太极
  • instanceof 在多态中是判断运行类型是否从属于 of后面的类的判断方法
Person p = new Student();  // 这里假设 Person 是父类,Student 是子类
if (p instanceof Person) { // p 的运行类型是Student,而Student是Person的子类,所以这里会输出
    System.out.println("p 是 Person 类型的实例");
}
if (p instanceof Student) {// p 的运行类型是Student,所以这里会输出
    System.out.println("p 是 Student 类型的实例");
}
  • 再举一个例子,假设有一个接口 Shape 和两个实现类 Circle 和 Rectangle,我们可以使用 instanceof 操作符来判断一个对象是否实现了 Shape 接口:
Shape shape = new Circle();  // 创建一个 Circle 类型的对象,并将其赋值给 Shape 类型的变量
if (shape instanceof Shape) {
    System.out.println("shape 实现了 Shape 接口");
}
if (shape instanceof Rectangle) {
    System.out.println("shape 是 Rectangle 类型的实例");
}
  • 上面的代码中,我们创建了一个 Circle 类型的对象,并将其赋值给 Shape 类型的变量 shape。使用 instanceof 操作符来判断 shape 是否实现了 Shape 接口和 Rectangle 类型的实例。由于 Circle 类型的对象实现了 Shape 接口,因此第一个 if 语句输出;而由于 shape 不是 Rectangle 类型的实例,第二个 if 语句不会执行。