Multiple choice technology

Given: 10. interface Foo {} 11. class Alpha implements Foo {} 12. class Beta extends Alpha {} 13. class Delta extends Beta { 14. public static void main( String[] args ) { 15. Beta x = new Beta(); 16. // insert code here 17. } 18. } Which code, inserted at line 16, will cause a java.lang.ClassCastException?

  1. Alpha a = x;

  2. Foo f = (Delta)x;

  3. Foo f = (Alpha)x;

  4. Beta b = (Beta)(Alpha)x;

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

x is a Beta object. Casting it to Delta (a subclass) fails at runtime with ClassCastException because the actual object is not a Delta. You cannot cast an object to a subclass type it doesn't actually instantiate.