Java OCA OCP Practice Question 2659

Question

Given:

1. public class Main extends Shape {  
2.   Main() { s = "Main"; }  
3.   public static void main(String[] args) { new Main().go(); }  
4.    void go() {  
5.     Shape[] ba = { new Shape(), new Main(), (Shape) new Main() };  
6.     for(Shape b: ba)  System.out.print(b.getShape().s + " ");  
7.   }  //w ww  .  j a  v a 2  s . com
8.   Main getShape() { return this; }  
9. }  
10. class Shape {  
11.   String s;  
12.   Shape() { s = "Shape"; }  
13.   Shape getShape() { return this; }  
14. } 

What is the result?

  • A. Shape Main Shape
  • B. Shape Main Main
  • C. Shape Main followed by an exception.
  • D. Compilation fails due to an error at line 5.
  • E. Compilation fails due to an error at line 6.
  • F. Compilation fails due to an error at line 8.
  • G. Compilation fails due to an error at line 13.


B is correct.

Note

Line 5 is declaring a Shape array and assigning three Shape-ish objects to it.

The third object created in line 5 was created as type Main, and then upcast to type Shape, but the value of its String didn't change when it was upcast.

Next, Main's overriding getShape() method is using a legal (as of Java 5) covariant return.




PreviousNext

Related