首先需要确定的是 instanceof 的用法在java和JavaScript中的用法是天差地别的
一、instanceof 之 java
java中 instanceof 运算符返回的是一个boolean类型,是用来在运行时判断某对象是否是特定类(或者它子类)的一个实例
用法boolean = Object instanceof class
下面我们举个例子来详细说明instanceof的用法
首先建立一个接口,一个实现类,一个子类,具体关系看下面代码
/**
* Created by yan on 2019/1/19.
*/
public interface Person {
}
--------------------------------------------------------------------------------
/**
* Created by yan on 2019/1/19.
*/
public class Father implements Person {
}
--------------------------------------------------------------------------------
/**
* Created by yan on 2019/1/19.
*/
public class Son extends Father {
}
建立一个测试类
public class demo {
public static void main(String[] args) {
/*在编译状态中,class可以是object对象的父类,自身类,子类。在这三种情况下Java编译时不会报错。
在运行转态中,class可以是object对象的父类,自身类,不能是子类。在前两种情况下result的结果为true,*/
Person person = new Father();
Father father = new Father();
Son son = new Son();
System.out.println(father instanceof Person);
System.out.println(son instanceof Person);
System.out.println(father instanceof Son);
System.out.println(son instanceof Father);
System.out.println(person instanceof Person);
}
}
OutPut: