一起学Java(四十四)----- instanceof关键字

不积跬步,无以至千里;不积小流,无以成江海。

Java语言基础

Java的instanceof关键字

用来测试一个对象是否为一个类的实例,格式:

boolean result = obj instanceof Class

 其中 obj 为一个对象,Class 表示一个类或者一个接口,当 obj 为 Class 的对象,或者是其直接或间接子类,或者是其接口的实现类,结果result 都返回 true,否则返回false。

注意:

1. obj 必须为引用类型,不能是基本类型;

int i = 0;
System.out.println(i instanceof Integer);
System.out.println(i instanceof Object);

 两个都编译不通过,instanceof 运算符只能用作对象的判断。

2. 当 obj 为 null 时;

在 JavaSE规范 中对 instanceof 运算符的规定就是:如果 obj 为 null,那么将返回 false。

3. obj 为 class 类的实例对象;

Integer integer = new Integer(1);
System.out.println(integer instanceof  Integer); //true

 最普遍的一个用法。

4. obj 为 class 接口的实现类;

a. 用 instanceof 运算符判断 某个对象是否是 List 接口的实现类,如果是返回 true,否则返回 false

ArrayList arrayList = new ArrayList();
System.out.println(arrayList instanceof List); //true

 b. 反过来

List list = new ArrayList();
System.out.println(list instanceof ArrayList); //true

5. obj 为 class 类的直接或间接子类;

我们新建一个父类 Person.class,然后在创建它的一个子类 Man.class

public class Person {
 
}
public class Man extends Person{
     
}

 测试:

Person p1 = new Person();
Person p2 = new Man();
Man m1 = new Man();
System.out.println(p1 instanceof Man); //false
System.out.println(p2 instanceof Man); //true
System.out.println(m1 instanceof Man); //true

博客借鉴:https://www.cnblogs.com/ysocean/p/8486500.html

猜你喜欢

转载自www.cnblogs.com/smilexuezi/p/12919392.html