0
Can you help me?
What is the difference between CONSTRUCTOR and INITIALIZER and what exactly do we need them for?
1 Antwort
0
A constructor will "build" an instance when it is call. And the initializer will be call on the load of the class. You can have two type of initializer. but it's will be better with code:
public class A {
static int staticVariable;
int instanceVariable;
// Static block:
static {
System.out.println("Static");
staticVariable = 5;
}
// Instance block:
{
System.out.println("Instance");
instanceVariable = 10;
}
// Constructor
public A() {
System.out.println("Constructor");
}
public static void main(String[] args) {
new A();
new A();
}
}
and the output will be:
Static
Instance
Constructor
Instance
Constructor
As we can see the static is load only one at the begining (normal it's static, call only of the first call of the class). After the instance and finally the constructor.