I know that static blocks are initialized at the time the class is loaded and since the class is loaded only once in a program,they are initialized only once.
IIB (Instance initialization blocks) are initialized every time an instance of the class is made, and the same for constructors: they are executed during object creation.
I don't understand why in the below program IIB is executed in prior to Constructors. Code-
public class Hello {
public static void main(String args[]) {
C obj = new C();
}
}
class A {
static {
System.out.println("Inside static block of A");
}
{
System.out.println("Inside IIB of A");
}
A() {
System.out.println("Inside NO-ARGS constructor of A");
}
}
class B extends A {
static {
System.out.println("Inside static block of B");
}
{
System.out.println("Inside IIB of B");
}
B() {
System.out.println("Inside NO-ARGS constructor of B");
}
}
class C extends B {
static {
System.out.println("Inside static block of C");
}
{
System.out.println("Inside IIB of C");
}
C() {
System.out.println("Inside NO-ARGS constructor of C");
}
}
Why IIB is executed first compared to constructors?
Instance Initialization blocks are executed whenever the class is initialized and before constructors are invoked. They are typically placed above the constructors within braces.
Instance block executes before the constructor only when an instance of the class is created.
Instance Initializer block is used to initialize the instance data member. It run each time when object of the class is created. The initialization of the instance variable can be done directly but there can be performed extra operations while initializing the instance variable in the instance initializer block.
Q1. What is the difference between constructor and instance initialization blocks ? Ans. Constructor has the same name as class name whereas instance initialization block just have a body without any name or visibility type.
Java compiler injects initializer blocks at the beginning of your constructors (after calling a superconstructor). To give you a better understanding I've compiled the following class
public class Foo extends SuperFoo {
private String foo1 = "hello";
private String foo2;
private String foo3;
{
foo2 = "world";
}
public Foo() {
foo3 = "!!!";
}
}
and run it through a javap decompiler:
Compiled from "Foo.java"
public class Foo extends SuperFoo {
private java.lang.String foo1;
private java.lang.String foo2;
private java.lang.String foo3;
public Foo();
Code:
0: aload_0
1: invokespecial #12 // Method SuperFoo."<init>":()V
4: aload_0
5: ldc #14 // String hello
7: putfield #16 // Field foo1:Ljava/lang/String;
10: aload_0
11: ldc #18 // String world
13: putfield #20 // Field foo2:Ljava/lang/String;
16: aload_0
17: ldc #22 // String !!!
19: putfield #24 // Field foo3:Ljava/lang/String;
22: return
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With