Java OCA OCP Practice Question 2762

Question

Given:

3. class Shape {  
4.   Shape play() { System.out.print("play "); return new Shape(); }  
5.   Shape play(int x) { System.out.print("play x "); return new Shape(); }  
6. }  /*from ww w .  ja v a2  s .co m*/
7. class Main extends Shape {  
8.   Main play() { System.out.print("baseball "); return new Main(); }  
9.   Shape play(int x) { System.out.print("sport "); return new Shape(); }  
10.  
11.   public static void main(String[] args) {  
12.     new Main().play();  
13.     new Main().play(7);  
14.     super.play(7);  
15.     new Shape().play();  
16.     Shape s = new Main();  
17.     s.play();      
18. } } 

What is the result?

  • A. baseball sport sport play play
  • B. baseball sport play x play sport
  • C. baseball sport play x play baseball
  • D. Compilation fails due to a single error.
  • E. Compilation fails due to errors on more than one line.


D is correct.

Note

The only error is on line 14: A call to super cannot be made from a static context.

The overridden play() method on line 8 is an example of a covariant return, which is a legal override as of Java 5.




PreviousNext

Related