Reputation: 1189
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
Upvotes: 0
Views: 129
Reputation: 213243
If you remove B b = new B()
, then your reference (A a)
declared as instance variable will not be initialized with the instance new 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: -
A a = new A(2);
Your above code is converted to: -
A a;
public B() {
super();
a = new A(2);
}
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 B
class, A a
will not be initalized and hence the constructor A(int i)
will not be invoked.
Upvotes: 5
Reputation: 46408
if you remove B b = new B()
from your main , only 1,4,3 will be printed.
in your class B only the objects marked static will be initialized as they dont require an instance of a class to initialize them. for your class B to invoke.
A a = new A(2);
you need to create an instance of that class, like you are doing in your code currently. if you remove it A a= new A(2)
will not be invoke thus, the output would be 1,4,3
Upvotes: 2