关于java里的instanceof运算符(总结于疯狂JAVA讲义)

        通过instanceof运算符运算后得到的结果为布尔类型。instanceof前一个操作数A通常是一个引用类型的变量,后一个操作数B通常是一个类或者接口,用于判断对象A是否是B的类,或者其子类、实现类的实例

'       在编译时,如果A的类型和B相同,或者是B的父类,编译才不会发生错误。例子程序如下:

public class Test{
    public static void main(String [] args){
        
                //Object 类是所有类的父类

                Object hello="Hello";

                //hello变量的实际类型是String,String是Object的子类,可以进行instanceof运算,返回true

                System.out.println("字符串是否是Object类的实例:"+(hello instanceof Object));

               // hello变量的实际类型是String,返回true

                System.out.println("字符串是否是String类的实例:"+(hello instanceof String));

               //Math是Object的子类,可以进行instanceof运算。返回false

                System.out.println("字符串是否是Math类的实例:"+(hello instanceof Math));

                //String实现了Comparable接口,返回true

                System.out.println("字符串是否是Comparable接口的实例:"+(hello instanceof Comparable));

                //hello变量的编译类型是Object,是String类型的父类,可以强制类型转换

                String x=(String) hello;

                //String类既不是Math类,也不是Math父类,所以下面的代码编译会发生错误"Incompatible conditional operand types String and Math"
              // System.out.println("字符串是否是Math类的实例:"+(x instanceof Math));
    }

}

instanceof的作用:在执行强制类型交换之前,首先判断前一个对象是否是后一个类的实例,是否可以成功地转换,从而保证代码更加健壮。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值