背景
应用后期特此纪要!
问题
Java中instanceof关键字的作用是什么?
说明
instanceof是Java中的一类关键字。
纪要
作用:用来判断内存中实际对象A是不是B类型,一般用来做类的类型判断。
Eg:
cat、dog继承自animal,tree继承自botany
cat instanceof animal 返回 true
dog instanceof cat 返回 false
cat instanceof botany 返回 false下面是两个Demo实例,可以运行参考:
package www.demo; /** * Cat * @author Administrator * */ class Cat extends Animal{ } /** * Dog * @author Administrator * */ class Dog extends Animal{ } /** * Animal * @author Administrator * */ class Animal { } public class Instanceof_test { public static void main(String[] args) { /** * 语法: boolean result = obj instanceof Class * 解析: * 1.obj为实际内存中的对象。Class为类或接口。[当obj为Class的对象,或者是其直接或间接子类,或者是其接口的实现类,都将返回true] * 2.编译时编译器会检查 obj 是否能转换成右边的class类型,如果不能转换则直接报错。 * 结论: * 1.obj必须是引用类型,不能是基本类型。 * 2.obj若为null,不论和什么类型instanceof都将返回false(null用instanceof跟任何类型比较时都是false)。 */ Cat cat = new Cat(); Dog dog = new Dog(); System.out.println(cat instanceof Animal); //true System.out.println(dog instanceof Animal); //true System.out.println(cat instanceof Cat); //true System.out.println(dog instanceof Dog); //true // System.out.println(cat instanceof Dog); // 编译不通过 “Incompatible conditional operand types Cat and Dog” } }
package www.demo; /** * Animal * @author Administrator * */ interface Animal { } /** * Cat * @author Administrator * */ class Cat implements Animal{ } /** * Dog * @author Administrator * */ class Dog implements Animal{ } public class Instanceof_test { public static void main(String[] args) { /** * 语法: boolean result = obj instanceof Class * 解析: * 1.obj为实际内存中的对象。Class为类或接口。[当obj为Class的对象,或者是其直接或间接子类,或者是其接口的实现类,都将返回true] * 2.编译时编译器会检查 obj 是否能转换成右边的class类型,如果不能转换则直接报错。 * 结论: * 1.obj必须是引用类型,不能是基本类型。 * 2.obj若为null,不论和什么类型instanceof都将返回false(null用instanceof跟任何类型比较时都是false)。 */ Cat cat = new Cat(); Dog dog = new Dog(); System.out.println(cat instanceof Animal); //true System.out.println(dog instanceof Animal); //true System.out.println(cat instanceof Cat); //true System.out.println(dog instanceof Dog); //true // System.out.println(cat instanceof Dog); // 编译不通过 “Incompatible conditional operand types Cat and Dog” } }