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

The actual object is a Beta instance (created with new Beta()). At runtime, you cannot cast a Beta object to Delta - they are sibling classes in the hierarchy, not in an inheritance relationship. The cast (Delta)x fails because x's actual type (Beta) cannot be converted to Delta. This throws ClassCastException. Options A, C, D are valid casts because Beta extends Alpha and implements Foo, so upcasting to Alpha or Foo is safe.