首先我么有这样的一张类图:
我们写出了类的基本继承关系:
<span style="font-family:SimSun;">class GoldenDelicious extends Apple{
public GoldenDelicious(){}
}
class Macintosh extends Apple{
public Macintosh(){}
}
class Apple extends Fruit{
public Apple(){}
}
class Orange extends Fruit{
public Orange(){}
}
class Fruit{
public Fruit(){}
}</span>
现在实例化对象
<span style="font-family:SimSun;">Fruit fruit = new GoldenDeclicious();
Orange orange = new Orange();
</span>
这样,我们使用GoldenDeclicious类实例化一个fruit对象;使用Orange类实例化一个orange对象。
下面测试:
<span style="font-family:SimSun;"> System.out.println(fruit instanceof Fruit); //true
System.out.println(fruit instanceof Orange); //false
System.out.println(fruit instanceof Apple); //true
System.out.println(fruit instanceof GoldenDelicious); //true
System.out.println(fruit instanceof Macintosh); //false
System.out.println(orange instanceof Fruit); //true
System.out.println(Apple.class.isInstance(orange)); //false</span>
结果:
true
false
true
true
false
false
true
false
现在我们首先明白instanceof表示的意思是 A instanceof B 表示A是B 的实例,返回为true或false,现在我们来分析结果:
<span style="font-family:SimSun;"><pre name="code" class="java"><pre name="code" class="java">
System.out.println(fruit instanceof Fruit); //true
<pre name="code" class="java"> System.out.println(fruit instanceof Apple); //true
System.out.println(fruit instanceof GoldenDelicious); //true </span>
因为fruit是用GoldenDeclicious实例化的,fruit是GoldenDelicious的对象,是Apple的子类对象,也是Fruit的子类对象,所以上面三个都是true.。
<span style="font-family:SimSun;">System.out.println(fruit instanceof Orange); //false
<pre name="code" class="java">System.out.println(fruit instanceof Macintosh); //false </span>
同时fruit不是Orange类的对象,也不是它的子类对象,同理,所以上面为false.
<span style="font-family:SimSun;">System.out.println(orange instanceof Fruit); //true</span>
因为orange是用Orange实例化的,所以orange是Fruit的子类对象,所以为true.
<span style="font-family:SimSun;">System.out.println(Apple.class.isInstance(orange)); //false</span>
这里之所以这么写,因为像之前那么写instanceof编译就会通不过,这样写可以在编译时不检查类型,显然这个结果是false.
最后,instanceof常用于多态中进行下转型进行类型判断。
例如:
<span style="font-family:SimSun;">public double calculate(Shape2D shape) {
if (shape instanceof Circle) {
Circle circle = (Circle) shape;
//……
} else if (shape instanceof Rectangle) {
Rectangle rectangle = (Rectangle) shape;
//……
} else if (shape instanceof Square) {
Square squre = (Square) shape;
//……
} else if (shape instanceof Triangle) {
Triangle triangle = (Triangle) shape;
//……
}
return 0;
}</span>