instanceof是运算符只被用于对象引用变量,检查左边的被测试对象是不是右边类或接口的实例化。
这里有两个方面进行解释:
1.语法:针对声明的类
声明被测试对象的类必须与右边类,要么是继承关系,要么是接口关系,否则会报错。如下:
[code="java"] public void TA(Cloneable e){
if(e instanceof String){
}
}
public void TA(E e){
if(e instanceof String){
}
}[/code]
这些无法通过eclipse的语法检测。
2.用法:针对创建的类实例化的类
通过1可以知道左面的声明类和右边的类应该有一个主次关系,但是左面用来实例化的类和右边不一定是主次关系,有可能是同一个父类的同一个子类。这样该运算符的用法就有两层含义:a)检测左面的实例化的类是否是左边的子类b)检测左面的实例化的类是否是其父类的某一个子类
package com.test.instanceof2;
class InstanceOf {
public static void main(String args[]) {
B b = new B();
C c = new C();
D d = new D();
E e = new E();
F f = new F();
H h = new H();
A g = new G();
if (b instanceof B)
System.out.println("b is instance of B");
if (c instanceof C)
System.out.println("c is instance of C");
if (c instanceof A)
System.out.println("c can be cast to A");
if (c instanceof B)
System.out.println("c can be cast to B");
if (d instanceof A)
System.out.println("d can be cast to A");
if (d instanceof B)
System.out.println("d can be cast to B");
if (g instanceof E)
System.out.println("d can be cast to B");
System.out.println();
A ob;
ob = d; // A reference to d
System.out.println("ob now refers to d");
if (ob instanceof D)
System.out.println("ob is instance of D");
System.out.println();
ob = c; // A reference to c
System.out.println("ob now refers to c");
if (ob instanceof D)
System.out.println("ob can be cast to D");
else
System.out.println("ob cannot be cast to D");
if (ob instanceof A)
System.out.println("ob can be cast to A");
System.out.println();
// all objects can be cast to Object
if (b instanceof Object)
System.out.println("b may be cast to Object");
if (c instanceof Object)
System.out.println("c may be cast to Object");
if (d instanceof Object)
System.out.println("d may be cast to Object");
}
public void TA(Object e){
if(e instanceof String){
}
}
}
interface A {
}
class B {
int i, j;
}
class C extends B implements A {
int k;
}
class D extends B implements A {
int k;
}
class E extends B {
int k;
}
class F extends B {
int k;
}
class G implements A{
}
class H implements A{
}