I would like to understand how instanceof works.
Consider the following code:
class A { }
class B extends A { }
class C extends B { }
class D extends C { }
public class TestClass{
public static void main(String args[]){
B b = new C(); //1
A a = b; //2
if (a instanceof A) System.out.println("A"); //3
if (a instanceof B) System.out.println("B"); //4
if (a instanceof C) System.out.println("C"); //5
if (a instanceof D) System.out.println("D"); //6
}
}
Correct me if I'm wrong here, in order for instanceof to return true, the IS-A condition must be satisfied. If you take a look at line //1. At runtime, the program knows that the object denoted by reference "a" is of type C. Therefore, shouldn't only condition at line //5 be in the output? Why are A and B also in the output?
D not being displayed is because the object is not an instance of D and so there's no confusion there. But I don't understand why A and B are displayed in the console.
ais anAbecauseC extends B extends A.ais anBbecauseC extends B.ais aCbecause, well, it is.ais not aDbecauseD extends Candais aC.instanceofall the super classes in the hierarchy (till Object.java) and also for all the interfaces implemented by it and by the super classes in the hierarchy. I have included the various cases forinstanceof. Hopefully it will be helpful.