title: Java InstanceOf Output
body: <p>I would like to understand how instanceof works. </p>
  
  <p>Consider the following code:</p>
  
  <pre><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
      }
  }
  </code></pre>
  
  <p>Correct me if I'm wrong here, in order for <em>instanceof</em> 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? </p>
  
  <p>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. </p>