前一篇Blog我们在复写equals方法时提到了instanceof,接下来我们来了解下怎么使用instanceof。
1.定义
instanceof是一个二元操作符(运算符),和==,>,<是同一类东西。由于它是由字母组成的,所以也是Java的保留关键字。
2.作用
instanceof通过返回一个布尔值来指出,这个对象是否是这个特定类或者是它的子类的一个实例。
3.用法
result = object instanceof class
4.参数
Result:布尔类型。
Object:必选项。任意对象表达式。
Class:必选项。任意已定义的对象类。
5.说明
如果 object 是 class 的一个实例,则 instanceof 运算符返回 true。如果 object 不是指定类的一个实例,或者 object 是 null,则返回 false。
6.示例
public class InstanceofDemo {
static A a = null;
static B b = null;
static boolean res;
public static void main(String[] args) {
case_1();
case_2();
case_3();
}
public static void case_1(){
sop("-----instanceoftest test case 1: -------------");
res = a instanceof A;
sop("\ta instanceof A: " + res);
res = b instanceof B;
sop("\tb instanceof B: " + res);
}
public static void case_2(){
sop("\n-----instanceoftest test case 2: -------------");
a = new B();
b = new B();
res = a instanceof A;
sop("\ta instanceof A: " + res);
res = a instanceof B;
sop("\ta instanceof B: " + res);
res = b instanceof A;
sop("\tb instanceof A: " + res);
res = b instanceof B;
sop("\tb instanceof B: " + res);
}
public static void case_3(){
sop("\n-----instanceoftest test case 3: -------------");
B b2 = new C();
res = b2 instanceof A;
sop("\tb2 instanceof A: " + res);
res = b2 instanceof B;
sop("\tb2 instanceof B: " + res);
res = b2 instanceof C;
sop("\tb2 instanceof C: " + res);
}
public static void sop(Object obj) {
System.out.println(obj);
}
}
interface A {
}
class B implements A {
}
class C extends B {
}
输出结果为:
-----instanceoftest test case 1: -------------
a instanceof A: false
b instanceof B: false
-----instanceoftest test case 2: -------------
a instanceof A: true
a instanceof B: true
b instanceof A: true
b instanceof B: true
-----instanceoftest test case 3: -------------
b2 instanceof A: true
b2 instanceof B: true
b2 instanceof C: true
以上结果以此表明:对象引用不是对象的子类或是实例,所以显示输出为false。而当指定的引用是该对象的子类或是实例,就会返回true。