Which code, inserted at line 16, will cause a java.lang.ClassCastException?

Given:

interface Foo {}
class Alpha implements Foo {}
class Beta extends Alpha {}
class Delta extends Beta {
public static void main( String[] args ) {
Beta x = new Beta();
16. //insert code here
}
}

Which code, inserted at line 16, will cause a java.lang.ClassCastException?

Given:

interface Foo {}
class Alpha implements Foo {}
class Beta extends Alpha {}
class Delta extends Beta {
public static void main( String[] args ) {
Beta x = new Beta();
16. //insert code here
}
}

Which code, inserted at line 16, will cause a java.lang.ClassCastException?

A.
Alpha a = x;

B.
Foo f = (Delta)x;

C.
Foo f = (Alpha)x;

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

Explanation:
A:
compiled successfully

B:
Exception in thread “main” java.lang.ClassCastException: Beta cannot be cast to Delta
at Delta.main(Main.java:16)

C:
compiled successfully

D:
compiled successfully



Leave a Reply 0

Your email address will not be published. Required fields are marked *