Java OCA OCP Practice Question 2847

Question

Given:

class Shape {   
  static String name = "gf ";  
  String doShape() { return "grandf "; }  
}  /* w w  w . j a va  2 s.c o m*/
class Rectangle extends Shape {  
  static String name = "fa ";  
  String doShape() { return "father "; }  
}  
public class Main extends Rectangle {  
   static String name = "ch ";  
   String doShape() { return "child "; }  
   public static void main(String[] args) {  
     Rectangle f = new Rectangle();  
     System.out.print(((Shape)f).name  
                    + ((Shape)f).doShape()) ;  
     Main c = new Main();  
     System.out.println(((Shape)c).name  
                    + ((Shape)c).doShape() + ((Rectangle)c).doShape());  
 } } 

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

A.   Compilation fails.
B.   fa father ch child child
C.   gf father gf child child
D.   fa grandf ch grandf father
E.   gf grandf gf grandf father
F.   An exception is thrown at runtime.


C is correct.

Note

Overriding applies only to instance methods, therefore the reference variables' type is used to access the static Strings called "name".

During overriding, the object's type is used to determine which overridden method is used.




PreviousNext

Related