1、instanceof 比较左边的对象所指向的对象是不是右边类的一个实例(这里是使用类C++里的指针,java中没有指针,但是存储在堆栈中的对象的引用指向存储在堆中的对象,类似于C++中的指针)。也就是说左边的对象必须实例化之后,才有可能是右边类的一个实例。如下代码中,由于p并没有进行实例化,而只是一个对象的引用,所以p instanceof Parent 是false。
class Parent {}
public class Instanceof {
public static void main(String[] args) {
Parent p = null;
if(p instanceof Parent) {
System.out.println("p is the instance of Parent!");
}else {
System.out.println("p is not the instance of Parent!");
}
}
}
结果:p is not the instance of Parent!
2、任何继承自父类的一个子类的一个实例,都是父类的一个实例。
class Parent {}
class Child1 extends Parent {}
class Child2 extends Child1 {}
public class Instanceof {
public static void main(String[] args) {
Child2 child2 = new Child2();
if(child2 instanceof Parent) {
System.out.println("child2 is the instance of Parent!");
}else {
System.out.println("child2 is not the instance of Parent!");
}
}
}
结果:child2 is the instance of Parent!
3、父类的实例,不是子类的一个实例。
class Parent {}
class Child1 extends Parent {}
public class Instanceof {
public static void main(String[] args) {
Parent parent = new Parent();
if(parent instanceof Child1) {
System.out.println("parent is the instance of Child1!");
}else {
System.out.println("parent is not the instance of Child1!");
}
}
}
结果:parent is not the instance of Child1!