欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java instanceof 运算符的使用方法

程序员文章站 2023-12-09 21:56:33
用法:   (类型变量 instanceof 类|接口) 作用:   instanceof 操作符用于判断前面的对象是否是后面的类,或者其子类、实现类的实例。如果是则...

用法:

  (类型变量 instanceof 类|接口)

作用:

  instanceof 操作符用于判断前面的对象是否是后面的类,或者其子类、实现类的实例。如果是则返回true 否则就返回false。

注意:

  · instanceof前面的操作数的编译时类型要么与后面的类相同,要么与后面的类具有父子继承关系否则会引发编译错误。

一个简单的例子:

复制代码 代码如下:

/**
 * instanceof 运算符
 * @author administrator
 *
 */

public class testinstanceof {
    public static void main(string[] args) {
        //声明hello 时使用object类,则hello的编译类型是object
        //object类是所有类的父类,但hello的实际类型是string
        object hello = "hello";

        //string是object的子类可以进行instanceof运算,返回true
        system.out.println("字符串是否为object类的实例:"
                + (hello instanceof object));

        //true
        system.out.println("字符串是否为string的实例:"
                + (hello instanceof string));

        //false
        system.out.println("字符串是否为math类的实例:"
                + (hello instanceof math));

        //string实现了comparable接口,所以返回true
        system.out.println("字符串是否为comparable类的实例:"
                +(hello instanceof comparable));

        /**
         * string 既不是math类,也不是math类的父类,故下面代码编译错误
         */
        //string a = "hello";
        //system.out.println("字符串是否为math类的实例:"
        //        + (a instanceof math));

    }
}


运行结果:

复制代码 代码如下:

字符串是否为object类的实例:true
字符串是否为string的实例:true
字符串是否为math类的实例:false
字符串是否为comparable类的实例:true

通常在进行强制类型转换之前,先判断前一个对象是不是后一个对象的实例,是否可以成功转换,从而保证代码的健壮性。