I have two classes Parent and Child
public class Parent {
public Parent() {
System.out.println("Parent Constructor");
}
static {
System.out.println("Parent static block");
}
{
System.out.println("Parent initialisation block");
}
}
public class Child extends Parent {
{
System.out.println("Child initialisation block");
}
static {
System.out.println("Child static block");
}
public Child() {
System.out.println("Child Constructor");
}
public static void main(String[] args) {
new Child();
}
}
The output of the above code will be
Parent static block
Child static block
Parent initialization block
Parent Constructor
Child initialization block
Child Constructor
Why does Java execute the code in that order? What are the rules that determine the execution order?
I learn visually, so here's a visual representation of order, as a SSCCE:
This prints:
Keep in mind that the order of the
static
parts matters; look back at the difference between the order ofExample
'sstatic
stuff andExampleSubclass
's.Also note that the instance initialization block is always executed before the constructor, no matter the order. However, order does matter between an initialization block and a field initializer.
Static block in java is executed before main method. If we declare a Static block in java class it is executed when class loads. This is initialize with the static variables. It is mostly used in JDBC. Static block in java is executed every time when a class loads. This is also known as Static initialization block. Static block in java initializes when class load into memory , it means when JVM read the byte code. Initialization can be anything; it can be variable initialization or anything else which should be shared by all objects of that class. Static block is a normal block of code enclosed in braces { } and is preceded by static keyword.
so static block executed first.
Instance Initialization Blocks: Runs every time when the instance of the class is created.
so next Initialization block executed when instance of the class is created.
then Constructor executed
Just wanted to share my findings. I read in one of the answers on another thread that static blocks are executed first before static fields which is not correct. It depends on which comes first, static field or static block. Have a look at below code. It will try to put things in perspective.
It comes back to main method.
Here is the output:
1.Static init block executes at the time of class loading only ones. 2.Init block executes every time before creating object of the class.
link :- https://www.youtube.com/watch?v=6qG3JE0FbgA&t=2s
It would be very helpful to ckeck out the object construction process with a step by step debuger, having a view in which you can see how your object is goning through the phases. I found this very useful for clearing the perspective from a higher point of view. Eclipse can help you with this with it's debugger step into function.