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= (Alpha)x;

  3. Foo f= (Delta)x;

  4. Beta b = (Beta)(Alpha)x;


Correct Option: C

AI Explanation

To answer this question, let's go through each option to understand why it is correct or incorrect:

Option A) Alpha a = x; - This option is incorrect because the object 'x' is of type Beta, which is a subclass of Alpha. Therefore, it can be assigned to a variable of type Alpha without any issue.

Option B) Foo f = (Alpha)x; - This option is incorrect because the object 'x' is of type Beta, which is a subclass of Alpha. The cast to Alpha is valid since Beta is a subclass of Alpha. Additionally, 'x' can be assigned to a variable of type Foo because Beta indirectly implements the Foo interface through its superclass Alpha.

Option C) Foo f = (Delta)x; - This option is correct because the object 'x' is of type Beta, and you are trying to cast it to Delta. Since Delta is not a superclass of Beta, this cast will result in a ClassCastException. It is not possible to cast an object to a type that is not in its inheritance hierarchy.

Option D) Beta b = (Beta)(Alpha)x; - This option is incorrect because the object 'x' is already of type Beta, so there is no need for the cast. The cast to Alpha is also unnecessary since Beta is a subclass of Alpha. Therefore, this code will not cause a ClassCastException.

The correct answer is Option C. This option will cause a java.lang.ClassCastException because you are trying to cast an object of type Beta to a type that is not in its inheritance hierarchy (Delta).

Find more quizzes: