Given That: 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;


Correct Option: B
Explanation:

To solve this question, the user needs to know about inheritance in Java and how casting works. The key to answering this question correctly is understanding how casting works between different classes in an inheritance hierarchy.

Now, let's go through each option and explain why it is right or wrong:

A. Alpha a = x; - This code is valid because Beta is a subclass of Alpha, so it can be upcast to an Alpha without issue. This will not cause a ClassCastException.

B. Foo f= (Delta)x; - This code is invalid because Delta is a subclass of Beta, so it cannot be downcast to Delta from Beta. This will throw a ClassCastException.

C. Foo f= (Alpha)x; - This code is valid because Beta is a subclass of Alpha, so it can be upcast to an Alpha without issue. This will not cause a ClassCastException.

D. Beta b = (Beta)(Alpha)x; - This code is invalid because Alpha is a superclass of Beta, so it cannot be downcast to Beta from Alpha. This will throw a ClassCastException.

Therefore, the correct answer is:

The Answer is: B

Find more quizzes: