Java OCA OCP Practice Question 810

Question

Consider the following code:

class MyBaseClass{ 
  static{ System .out.print ("super ");  } 
} 
class MyClass1{ //ww w .ja  v  a  2  s .co  m
  static  {  System .out.print ("one ");  } 
} 
class MyClass2 extends MyBaseClass{ 
  static  {  System .out.print ("two ");  } 
} 
public class Main{ 
  public static void main (String [] args){ 
     MyClass1 o = null; 
     MyClass2 t = new MyClass2 (); 
   } 
} 

What will be the output when class Main is run ?

Select 1 option

  • A. It will print one, super and two.
  • B. It will print one, two and super.
  • C. It will print super and two.
  • D. It will print two and super E. None of the above.


Correct Option is  : C

Note

A class or interface type T will be initialized immediately before the first occurrence of any one of the following:

  • T is a class and an instance of T is created.
  • T is a class and a static method declared by T is invoked.
  • A static field declared by T is assigned.
  • A static field declared by T is used and the field is not a constant variable.
  • T is a top-level class, and an assert statement lexically nested within T is executed.

The statement MyClass1 o = null; does not fall in either of the cases mentioned above.

So class MyClass1 is not initialized and its static block is not executed.

Class MyClass2 is initialized only after its super class MyBaseClass has been initialized.




PreviousNext

Related