Java OCA OCP Practice Question 2859

Question

Given:

3. class MyClass {  
4.   MyClass create() { return new MyClass(); }  
5. }   //from   w w  w. ja  v a2 s .c  om
6. public class Main extends MyClass {  
7.   Main create() { return new Main(); }  
8.   public static void main(String[] args) {  
9.     new Main().go(new Main());  
10.   }  
11.   void go(Main c) {  
12.     go2(new MyClass().create(), c.create());  
13.   }  
14.   void go2(MyClass b, Main c) {  
15.     Main c2 = (Main)b;  
16.     MyClass b2 = (MyClass)c;  
17. } } 

What is the result? (Choose all that apply.)

  • A. A ClassCastException is thrown at line 15.
  • B. A ClassCastException is thrown at line 16.
  • C. Compilation fails due to an error on line 7.
  • D. Compilation fails due to an error on line 12.
  • E. Compilation fails due to an error on line 15.
  • F. Compilation fails due to an error on line 16.


A is correct.

Note

The override on line 7 is a legal covariant return.

The attempted cast at line 15 is incorrect because Main instances might do more than MyClass instances.




PreviousNext

Related