Java OCA OCP Practice Question 3062

Question

Given:

2. public class Main extends Rectangle {  
3.   String print() { return "feed me "; }  
4.   public static void main(String[] args) {  
5.     Shape[] shapes = new Shape[3];  
6.     shapes[0] = new Rectangle();  
7.     shapes[1] = (Shape)new Main();  
8.     shapes[2] = (Shape)new Rectangle();  
9.     for(Shape d: shapes)  System.out.print(d.print());  
10. } }  /*from   w  w  w.  j a v a2  s  .  c  om*/
11. class Shape { String print() { return "print "; } }  
12. class Rectangle extends Shape { String print() { return "woof "; } } 

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

  • A. print print print
  • B. woof print print
  • C. woof feed me woof
  • D. Compilation fails due to an error on line 6.
  • E. Compilation fails due to an error on line 7.
  • F. Compilation fails due to an error on line 8.
  • G. Compilation fails due to an error on line 9.


C is correct.

Note

All the code is legal, and line 9 is using a for-each loop.

The polymorphic invocations of print() use the version of print() that corresponds with the object's type, not the reference variable's type.




PreviousNext

Related