title: Cast a superclass to a subclass
body: <p>Imagine a class <strong>Cottage extending Building</strong> and the code</p>
  
  <pre><code>Building building = new Building();
  Cottage cottage = (Cottage)building;
  </code></pre>
  
  <p>Now, it totally makes sense that <strong>Building</strong> cannot be casted to <strong>Cottage</strong> considering the nature of java's inheritance, but what doesn't make sense (to me) is that this compiles. Why does it compile and then throw a runtime <strong>ClassCastException</strong>?  </p>
  
  <p>Isn't it obvious that <strong>building</strong> is a reference to a <strong>Building</strong> object before actually running the program?</p>
  
  <p>Being such a general question, I know I am getting a possible duplicate for this one :) but I couldn't find an answer to WHY DOES IT COMPILE question :)</p>
  
  <p><strong>EDIT2</strong> I accepted a great answer here (let alone the discussion below it :) ), but I still find the accepted answer in <a href="https://stackoverflow.com/questions/10388136/java-casting-resulting-in-run-time-error-instead-of-compilation-error">Java casting resulting in run-time error instead of compilation error</a> the most interesting...</p>
  
  <p><strong>EDIT</strong> I edited <strong>IllegalCastException</strong> and put the correct <strong>ClassCastException</strong></p>