Java OCA OCP Practice Question 130

Question

Given:

class Animal { //from  w w  w .  j a va  2s  . c o m
  { System.out.print("b1 "); } 
  public Animal() { 
      System.out.print("b2 "); 
  } 
} 
class Fish extends Animal { 
  
  static { System.out.print("r1 "); } 
  
  public Fish() { System.out.print("r2 "); } 
  
  { System.out.print("r3 "); } 
  
  static { System.out.print("r4 "); } 
} 
class SmallFish extends Fish { 
  public static void main(String[] args) { 
    System.out.print("pre "); 
    new SmallFish(); 
    System.out.println("hawk "); 
  } 
} 

What is the result?

  • A. pre b1 b2 r3 r2 hawk
  • B. pre b2 b1 r2 r3 hawk
  • C. pre b2 b1 r2 r3 hawk r1 r4
  • D. r1 r4 pre b1 b2 r3 r2 hawk
  • E. r1 r4 pre b2 b1 r2 r3 hawk
  • F. pre r1 r4 b1 b2 r3 r2 hawk
  • G. pre r1 r4 b2 b1 r2 r3 hawk
  • H. The order of output cannot be predicted
  • I. Compilation fails


D is correct.

Note

Static init blocks are executed at class loading time; instance init blocks run right after the call to super() in a constructor.

When multiple init blocks of a single type occur in a class, they run in order, from the top down.




PreviousNext

Related