Java OCA OCP Practice Question 773

Question

What will the following code print when Main is run?

class Shape  { 
     //from   ww w  . j  a va2 s  . c om
  static int i = 10;   { 
      i = 15; 
      System .out.print (" Shape "+i); 
   } 
  static  { System .out.print (" Shape static "+i);  }     
} 

class Rectangle extends Shape  {  
  static  { 
    i = 45; 
    System .out.print (" Rectangle static "); 
   }{ 
    i = 30; 
    System .out.print (" Rectangle "+i); 
   } 
} 

class Square extends Rectangle{ 
  static  { System .out.println ("Square");  } 
} 

public class Main  {  
  public static void main (String [] args)  { 
      Rectangle m = new Rectangle (); 
   } 
} 

Select 1 option 

A. Shape static 10 Rectangle static Shape 10 Rectangle 30 
B. Shape static 10 Rectangle static Square Rectangle 30 
C. Shape static 10 Rectangle static Shape 15 Rectangle 30 
D. Shape static 10 Rectangle static 15 Rectangle 20 
E. It will not compile. 


Correct Option is  : C

Note

Although there is more to it that the following sequence, this is all you need to know :

  • Static blocks of the base class (only once, in the order they appear in the class).
  • Static blocks of the class.
  • Non-static blocks of the base class.
  • Constructor of the base class.
  • Non-static blocks of the class.
  • Constructor of the class.
  • Derived class's static or non-static blocks are not executed if that class is not being used.



PreviousNext

Related