Java OCA OCP Practice Question 2329

Question

What is the output of the following code?

class Shape { 
    String wood = "Shape"; 
    public Shape() { 
        wood = "Shape"; 
    } /*w w w  . j  ava  2 s. c o  m*/
    { 
        wood = "init:Shape"; 
    } 
} 
class Main extends Shape { 
    String main; 
    { 
        main = "init:Main"; 
    } 
    public Main() { 
        main = "Main"; 
    } 
    public static void main(String args[]) { 
        Main main = new Main(); 
        System.out.println(main.wood); 
        System.out.println(main.main); 
    } 
} 
a  init:Shape //  ww  w. j  av a 2s .  c  o m
   init:Main 

b  init:Shape 
   Main 

c  Shape 
   init:Main 

d  Shape 
   Main 


d

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 Shape.

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

class Shape 
{ 
    public Shape() 
    { /*from  w  w w . j  av a  2  s .  co  m*/
        wood = "Shape";           // initial initialization 
        wood = "init:wood";      // re-assignment by the initializer block 
        wood = "Shape";           // re-assignment by the constructor 
    } 
    String wood; 
} 



PreviousNext

Related