This is the snippet of Java code.
class A{
public A() { }
public A(int i) { System.out.println(i ); }
}
class B{
static A s1 = new A(1);
A a = new A(2);
public static void main(String[] args){
B b = new B();
A a = new A(3);
}
static A s2 = new A(4);
}
The execution order is the following: 1,4,2,3 because the initialization of class performed in this way.
But what if you remove the B b = new B(); object creation, does that mean that the class will not be initialized in the above order?
Best regards
If you remove
B b = new B(), then your reference(A a)declared as instance variable will not be initialized with the instancenew A(2)Only static variables are loaded and initialized at the time of class loading. Instance variable are initialized only when you instantiate your class.
Reason is: –
Your above code is converted to: –
by the compiler. Where
B()is the default constructor provided by compiler, since you have not provided your own. If you have declared your own constructor, then the initialization is added to each of your constructor.So, if you don’t instantiate your
Bclass,A awill not be initalized and hence the constructorA(int i)will not be invoked.