title: Understanding Multiple Casting in Java
body: <p><em>Skip to the last sentence if you want to read the question right away.</em></p>
  
  <p>Suppose we have an Interface and three classes:</p>
  
  <pre><code>interface I{}
  
  class A implements I{}
  
  class B extends A {}
  </code></pre>
  
  <p>And the following declarations:</p>
  
  <pre><code>A a = new A();
  B b = new B();
  </code></pre>
  
  <p>Now, there's the classic way of casting which allows me to cast a reference of type A (the parent class) to an object of type B (the child class) like this:</p>
  
  <pre><code> a = b; //here a is no longer pointing at object A, and is now pointing at the same object b is pointing at.
   b = (B) a; // the casting is now accepted by the compiler and during runtime as well.
  </code></pre>
  
  <p>Here where lies the problem though. Every time I see a line of code with multiple casting, I fail to read it (literally) and, as a result, I can't understand what it means.</p>
  
  <p>For instance, let's say we have this line of code:</p>
  
  <pre><code>a = (B)(I)b;
  </code></pre>
  
  <p>How would you read this one? <code>a</code> is a reference to an object of type A, and it is being assigned the value of an object of type B (first cast from the left). But wait a minute, there's also another cast (I) preceding b. So what do we have here? Is it an interface being cast as a (B) object? or is it a b being cast as an interface which is also being cast as a (B)?</p>
  
  <p>I tried to break it down to avoid confusion:</p>
  
  <pre><code>I temp = (I) b;// first line
  a = (B) temp;// second line
  </code></pre>
  
  <p>So, first, since b is an I (because it extends A which implements I), "first line" is accepted by the compiler and during runtime. </p>
  
  <p>"Second line" though, we have a reference to an object A being assigned a value of type B. At first glance, there's nothing wrong with it. But then I realized <code>I</code> is not an A nor is it a B, and even though the cast in "second line" can dupe the compiler into believing it's an object of type B, it shouldn't be accepted at runtime.</p>
  
  <p>So the main question that I would like an answer to is how do I interpret the following line:</p>
  
  <pre><code>a = (B)(I)b;
  </code></pre>