Java OCA OCP Practice Question 2313

Question

What is the output of the following code?

class MyClass { //w  w w .ja va2s . c  o m
    public MyClass() { 
        System.out.println("MyClass"); 
    } 
    { 
        System.out.println("MyClass:init"); 
    } 
} 
class Main extends MyClass { 
    { 
        System.out.println("Main:init"); 
    } 
    public Main() { 
        System.out.println("Main"); 
    } 
    public static void main(String args[]) { 
        new Main(); 
    } 
} 
a  MyClass:init //from  w  w w.  j  a va 2  s. c  om
   MyClass 
   Main:init 
   Main 

b  MyClass 
   MyClass:init 
   Main:init 
   Main 

c  MyClass:init 
   Main:init 
   MyClass 
   Main 

d  MyClass 
   MyClass:init 
   Main 
   Main:init 


a

Note

When a class is compiled, the contents of its initializer block are added to its constructor, just before its own contents.

For example, here's the decompiled code for class MyClass.

As you can see, the contents of its initializer block are added to its constructor:.

class MyClass 
{ 
    public MyClass() 
    { 
        System.out.println("MyClass:init"); 
        System.out.println("MyClass"); 
    } 
} 



PreviousNext

Related