Java Instanceof

Java Instanceof

Instanceof是一个非常简单的运算符,前一个操作通常是一个引用类型的变量,后一个操作数通常是一个类(也可以是接口,可以把接口理解成一种特殊的类),它用于判断前面的对象是否是后面的类或其子类,实现类的实例。如果是,返回true,否则,返回false。

public class InstanceTest {

     public static void main(String[] args){

       Object hello = "Hello";

       System.out.println(hello instanceof Object);

       System.out.println(hello instanceof String);

       System.out.println(hello instanceof Math);

       System.out.println(hello instanceof Comparable);

       String str = "hello";

       System.out.println(str instanceof Object);

       //System.out.println(strinstanceof Math);

       System.out.println(hello instanceof java.io.Serializable);

     }

}

Output:

true

true

false

true

true

true

System.out.println(strinstanceof Math);则编译错误是因为instanceof运算符有一个限制,编译时类型必须是如下3种情况:

要么与后面的类相同;要么是后面类的子类;要么是后面类型的子类。

如果前面操作数的编译时类型与后面的类型没有任何关系,程序将没发通过编译。

在运行阶段,被转型变量所引用对象的实际类型必须是目标类型的实例,或者是目标类型的子类,实现类的实例,否则在运行时将引发ClassCastException异常。

public class InstanceTest {

     public static void main(String[] args){

       Object hello = "Hello";

       String objStr = (String)hello;

       System.out.println(objStr);

       Object objPri = new Integer(5);

       String str = (String)objPri;

       String s ="Java";    

     }

}

Exceptionin thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String

Hello

      at InstanceTest.main(InstanceTest.java:8)

无法从Integer转换成String类型。

 

 

public class InstanceTest {

     public static void main(String[]args){

       String s = null;

       System.out.println(s instanceof String);

     }

}

False

S定义为null,虽然null可以作为所有引用类型变量的值,但对于s引用变量而言,它实际并未引用一个真正的String对象,因此程序输出false。

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值