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?
-
Alpha a = x;
-
Foo f= (Delta)x;
-
Foo f= (Alpha)x;
-
Beta b = (Beta)(Alpha)x;
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.