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?
B is correct.
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.