Multiple choice technology programming languages

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

Option B causes ClassCastException because x is a Beta object, and you cannot cast a Beta to Delta (Delta is a subclass of Beta, not the other way around). At runtime, when the JVM tries to cast the Beta object to Delta, it fails because the actual object is not a Delta. Options A, C, and D are valid casts that don't throw exceptions - Beta to Alpha is upcasting, Beta to Foo is valid (Beta implements Foo through Alpha), and the double cast in D is just a redundant upcast then downcast back to Beta.