Multiple choice technology programming languages

Question 5 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. B. Foo f= (Delta)x;

  2. A. Alpha a = x;

  3. D. The code on line 31 throws an exception.

  4. C. Foo f= (Alpha)x; D. Beta b = (Beta)(Alpha)x;

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

x is a Beta object. Option B: Foo f = (Delta)x attempts to cast Beta to Delta, which is not valid since Beta cannot be cast to its subclass Delta. This causes ClassCastException. Option A: Alpha a = x is valid upcast. Option C and D are less direct. The claimed answer A (B) is correct.

AI explanation

x is declared as Beta x = new Beta(); — the actual runtime object is a Beta, not a Delta. Option B, Foo f = (Delta)x;, tries to downcast that Beta object to Delta (a subclass further down the hierarchy). Since the real object isn't actually a Delta instance, this cast fails at runtime with ClassCastException. Alpha a = x; is a safe implicit upcast (Beta IS-A Alpha, no exception). Casting (Alpha)x then (Beta)(Alpha)x is also safe because the object really is a Beta underneath, so both casts succeed — no exception in that combined option.