Initialization block values ββare assigned before the constructor assigns them.
So, first init member 1 will be assigned, and then init member 2 will be assigned.
Consider this example from theJavaGeek
class InitBlocksDemo { private String name ; InitBlocksDemo(int x) { System.out.println("In 1 argument constructor, name = " + this.name); } InitBlocksDemo() { name = "prasad"; System.out.println("In no argument constructor, name = " + this.name); } static { System.out.println("In first static init block "); } { System.out.println("In first instance init block, name = " + this.name); } { System.out.println("In second instance init block, name = " + this.name); } static { System.out.println("In second static int block "); } public static void main(String args[]) { new InitBlocksDemo(); new InitBlocksDemo(); new InitBlocksDemo(7); } }
This conclusion,
In first static init block In second static int block In first instance init block, name = null In second instance init block, name = null In no argument constructor, name = prasad In first instance init block, name = null In second instance init block, name = null In no argument constructor, name = prasad In first instance init block, name = null In second instance init block, name = null In 1 argument constructor, name = null
The program proceeds as follows.
- When the program starts, the
InitBlocksDemo class InitBlocksDemo loaded into the JVM. - Static initialization blocks are started when the class is loaded in the order in which they are displayed in the program.
- Now that the execution of the static block is complete, the
main method is encountered. - In the statement,
new InitBlocksDemo(); the no-argument constructor is called. - Since there is a default call to the default
super -argument constructor, control passes to the super ie Object class - After its completion, control returns to our class and begins to assign default values ββto instance variables. In this case, the variable name will be assigned as
null . - Now instance blocks will be executed in the order in which they are displayed in the program. We have not yet redefined the value for the name variable to print
null - After executing the instance blocks, control passes to the constructor. Here name = "prasadam"; will reassign a new value, so "prasad" will be printed in the constructor with no arguments
- 9. The operator
new InitBlocksDemo(7); invokes a constructor call with one argument. The rest of the process is the same. The only difference is that the name is not reset by the new value, so it prints null
source share