5.7.3 instanceof运算符

5.7.3 instanceof运算符

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

instanceof前面的引用变量的编译时类型要与后面的类相同或者有继承关系

在使用instanceof运算符时需要注意:

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

instanceof的前面的引用变量的运行时类型决定返回trueflase

如果instanceof前面的引用变量的运行时类型和后面的类一样,或者是后面类的子类,则返回true.

instanceof运算符的作用

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

先用instanceof判断再强制类型装换

instanceof(type)Java提供的两个相关的运算符,通常先用instanceof判断一个对象是否可以强制类型转换,然后再使用(type)运算符进行强制类型转换,从而保证程序不会出现错误

实例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
public class InstanceofTest {
public static void main(String[] args) {
Object hello = "Hello";
// hello的编译时类型是Object,可以使用instanceof运算符比较,
// hello的运算时类型是String,String类的对象是Object的实例,所以返回true
System.out.println((hello instanceof Object));
// hello的编译时类型时Object,Object和String具有继承关系,可以使用instanceof运算符比较
// hello的运行时类型是String,String类的对象是String的实例,所以返回true
System.out.println((hello instanceof String));
System.out.println("-------------------------------------------------");
// hello的编译时类型是Object,Object和Math具有继承关系,可以使用instanceof运算符比较
// hello的运行时类型是String,String类的对象不是math类型的实例,返回false
System.out.println((hello instanceof Math));
// hello的编译时类型是Object,Object和 接口 可以使用instanceof比较
// hello的运行时类型是String,String是Comparable接口的实现类,返回true
System.out.println(hello instanceof Comparable);
System.out.println("-------------------------------------------------");
String a = "Hello";
// a的编译时类型是String,String和Math没有继承关系,无法比较,编译不通过
// System.out.println((a instanceof Math));
// a的编译时类型是String,String和Object具有继承关系,可以使用instanceof运算比较.
System.out.println(a instanceof Object);
System.out.println("-----------------------------------------------");
Father father = new Father();
// father的编译时类型是Father,Father和Son有继承关系,可以使用instanceof比较.
// father的运行时类型是Father,Father不是Son的子类,所以返回false
System.out.println(father instanceof Son);
father = new Son();
// father的运行时类型是Son,Son和相等Son,返回true
System.out.println(father instanceof Son);
}
}

class Father {
}

class Son extends Father {

}
1
2
3
4
5
6
7
8
9
10
true
true
-------------------------------------------------
false
true
-------------------------------------------------
true
-----------------------------------------------
false
true