In Java, we have two types of blocks: static block and instance block, and can declare many different constructors. What is the order of execution of blocks, constructors in Java? In this tutorial, let’s learn together!
A static block is a block of code that belongs to a particular class and does not belong to an instance of a class. We define it in the static keyword, for example:
1 2 3 4 5 6 7 8 |
package com.huongdanjava; public class StaticBlock { static { System.out.print("This is static block"); } } |
An instance block is a block of code, but it does not belong to the class, it belongs to the instance of the class. It is executed every time an instance of the class is initialized. We define it as follows:
1 2 3 4 5 6 7 8 |
package com.huongdanjava; public class InstanceBlock { { System.out.print("This is instance block"); } } |
And constructor, I do not need to say about it. You should know it, right :D.
So, what is the order of execution of the blocks, constructors? Let’s look at the code below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
package com.huongdanjava; public class Example { static { System.out.print("This is static block\n"); } { System.out.print("This is instance block\n"); } public Example() { System.out.print("This is constructor\n"); } public static void main(String[] args) { Example e = new Example(); } } |
Result:
Obviously, as you see, their execution order would look like this:
- The first is execute the code in the static block.
- Then will be in the instance block.
- And the code in the constructor will do after that.
So in the case of inheritance class as the following example, what should be for the order?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
package com.huongdanjava; public class Base { static { System.out.print("Base static block\n"); } { System.out.print("Base instance block\n"); } public Base() { System.out.print("Base constructor\n"); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
package com.huongdanjava; public class Derived extends Base { static { System.out.print("Derived static block\n"); } { System.out.print("Derived instance block\n"); } public Derived() { System.out.print("Derived constructor\n"); } public static void main(String[] args) { System.out.print("Main method\n"); Derived d = new Derived(); } } |
Result:
In this case, the order of precedence will be the parent class first and then the subclass. In principle, the static code blocks are still executable first.
In short:
- Static blocks will be run when the class is loaded into the JVM.
- Instance block will be run every time new instance of class is initialized.
- The instance block will run after the super constructor has run and before the current class’s constructor is run.