java instanceof
运算符用于测试指定对象是否是指定类型(类或子类或接口)的实例。
java中的instanceof
也称为类型比较运算符,因为它将类型与实例进行比较。 它返回true
或false
。 如果对任何具有null
值的变量应用instanceof
运算符,则返回false。
java instanceof的简单示例
下面来看看实例运算符的简单示例,它测试当前类。
class simple1 {
public static void main(string args[]) {
simple1 s = new simple1();
system.out.println(s instanceof simple1);// true
}
}
执行上面试代码,得到以下结果 -
true
子类类型的对象也是父类的类型。 例如,如果dog
扩展了animal
,那么dog
的对象可以通过dog
或animal
类来引用。
java instanceof运算符的另一个例子
class animal {
}
class dog1 extends animal {// dog inherits animal
public static void main(string args[]) {
dog1 d = new dog1();
system.out.println(d instanceof animal);// true
}
}
执行上面代码,得到以下结果 -
true
instanceof测试null值的变量示例
如果我们对具有null
值的变量应用instanceof
运算符,则返回false
。来看看下面给出的例子,将instanceof
运算符应用于具有null
值的变量。
class dog2 {
public static void main(string args[]) {
dog2 d = null;
system.out.println(d instanceof dog2);// false
}
}
执行上面代码,得到以下结果 -
false
使用java instanceof运算符的向下转换
当子类型引用父类的对象时,它被称为向下转换(downcasting)。 如果直接执行它,编译器会出现编译错误。 如果通过类型转换来执行,在运行时会抛出:classcastexception
。 但是如果使用instanceof
运算符,可以进行向下转换。
dog d=new animal();//compilation error
如果通过类型转换执行向下转换,则在运行时抛出:classcastexception
。
dog d=(dog)new animal();
//compiles successfully but classcastexception is thrown at runtime
使用instanceof进行向下转换
现在看看下面这个例子,通过instanceof
运算符进行向下转换。
class animal {
}
class dog3 extends animal {
static void method(animal a) {
if (a instanceof dog3) {
dog3 d = (dog3) a;// downcasting
system.out.println("ok downcasting performed");
}
}
public static void main(string[] args) {
animal a = new dog3();
dog3.method(a);
}
}
执行上面代码,得到以下结果 -
ok downcasting performed
向下转换不使用instanceof
也可以在不使用instanceof
运算符的情况下执行下转换,如以下示例代码所示:
class animal {
}
class dog4 extends animal {
static void method(animal a) {
dog4 d = (dog4) a;// downcasting
system.out.println("ok downcasting performed");
}
public static void main(string[] args) {
animal a = new dog4();
dog4.method(a);
}
}
执行上面代码,得到以下结果 -
ok downcasting performed
仔细看看,被引用的实际对象是dog
类的对象。 所以如果向下转换它,它是没有问题的。 但是,如果也可以这样写:
animal a=new animal();
dog.method(a);
//now classcastexception but not in case of instanceof operator
这是一个instanceof的终极示例,通过下面的例子中的代码看看instanceof
关键字的真正用法。
interface printable {
}
class a implements printable {
public void a() {
system.out.println("a method");
}
}
class b implements printable {
public void b() {
system.out.println("b method");
}
}
class call {
void invoke(printable p) {// upcasting
if (p instanceof a) {
a a = (a) p;// downcasting
a.a();
}
if (p instanceof b) {
b b = (b) p;// downcasting
b.b();
}
}
}// end of call class
class test4 {
public static void main(string args[]) {
printable p = new b();
call c = new call();
c.invoke(p);
}
}
执行上面代码,得到以下结果 -
b method