Hani Goc Hani Goc - 1 year ago 76
Java Question

Why is the output being printed after static init blocks (inheritance)

Problem description

The following piece of code which is taken from OCA/OCP Java SE 7 Programmer I & II Study Guide produces the following output:

r1 r4 pre b1 b2 r3 r2 hawk

My Solution which was wrong:
pre r1 r4 b1 b2 r3 r2 hawk

This is the logic that I followed:

  • First we start by printing
    which is before the instantiation of

  • What is in the
    blocks will be printed first:
    r1 r4

  • From the base class
    we print what is in the block then what is in the constructor :
    b1, b2

  • We move on to the first subclass
    and we print
    r3, r2

  • Finally we print
    which is in class

class Bird {
{System.out.print("b1 "); }
public Bird()
System.out.print("b2 ");
class Raptor extends Bird {
static { System.out.print("r1 "); }
public Raptor()
System.out.print("r2 ");
{ System.out.print("r3 "); }
static { System.out.print("r4 "); }
class Hawk extends Raptor {
public static void main(String[] args) {
System.out.print("pre ");
new Hawk();
System.out.println("hawk ");

Explanation of the solution which is provided by the book

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.


  • Static init blocks are executed at class loading time: It's also the class loading time of Hawk right? When class hawk is loaded it will automatically go up the inheritance tree? Even before printing

  • Why isn't the solution :
    r1 r4 b1 b2 r3 r2 pre hawk

  • It's like it went all the way up the inheritance to print what is in the
    methods then came all the way down to print
    . Then it went all the way up again to print what the in the
    . Then finally printed hawk.

It's a little confusing for me. Sorry If I butchered the java language.

Answer Source

b1 b2 r3 r2 are not static, so while they are indeed part of the construction of the instance, they will be called only after it's created (new Hawk(); which comes after pre)

Generally speaking, you are right about it going all the way up the ineritence tree, it does so twice:
- first time for the static part
- second time for the constructor stuff, triggered by creating new Hack, hence after the pre

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download