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
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 运算符前面的操作数的编译时类型必须是如下三种情况:
- 要么与后面的类型相同
- 要么是后面类型的父类
- 要么是后面类型的子类
如果前面的操作数的编译时类型与后面的类型没有任何关系,程序将出现编译错误!
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 的强制类型转换,在编译阶段,强制类型转换要求被转型变量是编译时类型必须是如下三种:
- 被转型变量的编译时类型与目标类型相同
- 被转型变量的编译时类型是目标类型的父类
- 被转型变量的编译时类型是目标类型的子类
在运行时阶段,被转型变量所引用的实际类型必须与目标类型有继承关系或者是目标类型!否则将抛出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