Multiple choice technology

What will happen if you attempt to compile and run the following code? class Base {} class Sub extends Base {} class Sub2 extends Base {} public class CEx{ public static void main(String argv[]){ Base b=new Base(); Sub s=(Sub) b; } }

  1. Compile and run without error

  2. Compile time Exception

  3. Runtime Exception

  4. none

Reveal answer Fill a bubble to check yourself
C Correct answer
Explanation

The code compiles because the cast from Base to Sub is syntactically allowed at compile time. However at runtime, b refers to a Base object (not a Sub), so the downcast fails with ClassCastException. You cannot cast an object to a type it isn't actually an instance of.