天天看点

Java 中 instanceof 运算符的使用场景Instanceof 运算符的含义     

Instanceof 运算符的含义     

       Java 中的 instanceof 运算符可以指出对象是否是特定类的一个实例。在具体的语句中,instanceof 左边是对象,右边是类。若该对象是右边类或子类所创建的,则返回 true ,否则返回 false。需要注意的是,instanceof 运算符左边的对象实例不可以是基础数据类型;null 与任何值进行运算均返回 false。

       例如下列代码段中,a 是接口 Test1 的实例对象引用指向子类 Test2,类 Test2 实现了接口Test1。因此两次输出的结果均为 true。

public interface Test1{
}

public class Test2 implements Test1{
}

public class Example{
    public static void main(String[] args){
        a = new Test2();
        b = new Test2();
        result = a instanceof Test1;
        System.out.println(result); 
        result = a instanceof Test2;
        System.out.println(result); 
    }
}