首页 > 编程笔记 > Java笔记 阅读:14

Java instanceof关键字的用法(附带实例)

instanceof 在 Java 中是一种比较特殊的关键字,用于检测某个对象是否是指定类、接口或子类的对象。

instanceof 关键字从字面上理解为“某对象是某类或某接口的实例吗?”,比如“A instanceof B”表示“对象 A 是类或接口 B 的实例吗?”。经过 instanceof 运算后会返回一个 boolean 类型的结果,表示是或否。

instanceof 的语法如下,左边是对象而右边是类或接口,返回 boolean 类型的结果:
boolean result = 对象 instanceof 类
boolean result = 对象 instanceof 接口
首先看检测类的情况。下面实例中,假设我们定义了 Person 类和 Animal 类,那么可以分别用 instanceof 运算符来检测各自的对象是否属于该类,输出结果都为 true。
public class InstanceofTest2 {
    public static void main(String[] args) {
        Person p = new Person();
        Animal a = new Animal();
        System.out.println(p instanceof Person);
        System.out.println(a instanceof Animal);
    }
}

class Person {
}
class Animal {
}

然后看检测子类的情况,继续定义一个 Woman 类继承 Person 类,然后分别创建 Person 类和 Woman 类的对象,如下所示:
public class InstanceofTest3 {
    public static void main(String[] args) {
        Person p = new Person();
        Woman w = new Woman();
        System.out.println(p instanceof Woman);
        System.out.println(w instanceof Person);
    }
}

class Woman extends Person {
}
“p instanceof Woman”运算的结果为 false,因为 Person 并非 Woman 的子类。“w instanceof Person”运算的结果为 true,因为 Woman 是 Person 的子类。

最后看检测接口的情况,先定义一个 Vehicle 接口,接着定义实现了 Vehicle 接口的 Bike 类,然后创建一个 Bike 类对象 b,实例代码如下:
public class InstanceofTest5 {
    public static void main(String[] args) {
        Bike b = new Bike();
        System.out.println(b instanceof Vehicle);
    }
}

interface Vehicle {
}

class Bike implements Vehicle {
}
“b instanceof Vehicle”结果为 true,因为对象 b 所属的类实现了 Vehicle 接口。

相关文章