instanceof 运算符 笔记

import java.io.*;


class Instanceof {
	public static void main(String[] args) {
		Object hello = "Hello";
		System.out.println("hello is a instance of Object "+(hello instanceof Object));


		System.out.println("hello is a instance of String "+(hello instanceof String));


		System.out.println("hello is a instance of Math "+(hello instanceof Math));
               //String 实现了Comparable接口
		System.out.println("hello is a instance of Comparable "+(hello instanceof Comparable));


		String str = "hello";


		//编译错误 提示str 是不可转换的类型
		//System.out.println("str is a instance of Math "+(str instanceof Math)); //1
               //String 实现了Serializable接口
		System.out.println("str is a instance of Serializable "+(str instanceof Serializable));
	}
}
上面的1处将出现编译错误! 注释掉后,运行结果为
hello is a instance of Object true
hello is a instance of String true
hello is a instance of Math false
hello is a instance of Comparable true
str is a instance of Serializable true
使用 instanceof 运算符 有个限制:instanceof 运算符前面的操作数的编译时类型必须是如下三种情况:
  1. 要么与后面的类型相同
  2. 要么是后面类型的父类
  3. 要么是后面类型的子类
如果前面的操作数的编译时类型与后面的类型没有任何关系,程序将出现编译错误!

import java.io.*;
class Instanceof {
	public static void main(String[] args) {
		Object str = "Thingking in java";
		Math math = (Math)str;//1
		//编译出错 提示 math是不可转换错误
		System.out.println("math is a instance of String "+(math instanceof String));//2
	}
}

上面编译出错!提示2处math是不可转换错误!1处没有提示错误!
对与java 的强制类型转换,在编译阶段,强制类型转换要求被转型变量是编译时类型必须是如下三种:
  1. 被转型变量的编译时类型与目标类型相同
  2. 被转型变量的编译时类型是目标类型的父类
  3. 被转型变量的编译时类型是目标类型的子类
如果被转型变量的编译时类型与目标类型没有任何继承关系,编译器则提示编译错误!
在运行时阶段,被转型变量所引用的实际类型必须与目标类型有继承关系或者是目标类型!否则将抛出ClassCastException异常!

instanceof 运算符 在编译时 只检查 操作数的 编译时类型,只要编译时类型符合要求则能通过编译,只要编译时类型不符合要求,即使其真实类型是目标类型 也通不过编译!
在运行时,则检查操作数的真实类型,如果真实类型不符合要求则抛出ClassCastException异常!


class Instanceof {
	public static void main(String[] args) {
		String str = null;
		System.out.println("null is a instance of String "+(str instanceof String));//false
	}
}

上面代码编译通过,运行时输出false
null 可以作为引用类型变量的值,str 编译时类型是String 所以能通过编译,运行时 str并未指向任何对象,因此输出false
instanceof 这个 功能可以保证操作数在转型时不为null,避免后面使用时出现NullPoiterException




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值