2
class parent {
    parent() {
        System.out.println("parent");
    }
}

public class child extends parent {
    {
        System.out.println("non static block");
    }
    child() {
        super();
        System.out.println("idk");
    }
    public static void main(String[] args) {
        new child();
    }
}

output:

parent
non static block 
idk

I was expecting output to be

non static block
parent 
idk

why didn't non static block run first??

HRJ
  • 17,079
  • 11
  • 56
  • 80
anuj
  • 31
  • 2
  • The first call in any java program after creating object is the Constructer of class. And that Constructer will call its super Constructer. – KP_JavaDev Nov 08 '15 at 05:45

3 Answers3

1

Non-static initializer blocks run each time when an object of your class is being constructed.

You can think of these blocks as of pieces of code shared among all of your class constructor - in the same way as initializers that invoke methods are shared among all of the constructors.

why didnt nonstatic block run first??

Non-static blocks run before the code of the constructor of your class, but after the code of the constructor of your base class. That's why you see non static block in between of parent printed by the constructor of the base class, and idk, which is printed by the constructor.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
0

Just to add one thing to answer @dasblinkenlight. This is called initializing instance member.

The Java compiler copies initializer blocks into every constructor. Therefore, this approach can be used to share a block of code between multiple constructors.

Alexander B.
  • 626
  • 6
  • 21
0

Once you create objet for any class its first call is to call there Constructer. Inside constructer it will call either this() or super().If there is any super class exist then constructer will call its super class constructer using super(). So in your example jvm calls first super class constructer and it execute if any code inside it. Also, if you place non-static block in super class that will be called before your current class static block.

Call sequence --> static block(if exist)--> all Non-static block -->Constructer--> all defined method()

Non-static blocks run every time when an object of your class is being created.

KP_JavaDev
  • 222
  • 2
  • 4
  • 11