A process that is executed once before using a class instance. Used when initializing class variables.
class initializer_demo {
//Class initializer
static {
//processing
}
//Instance initializer
{
//processing
}
}
When you think of the process of instantiating, the constructor comes to mind, The difference is that the instance initializer is executed before the constructor and the construct is executed after instantiation. If the constructor is overloaded and there are multiple constructors, the initializer seems to use it by executing common processing first.
Reference code below
class User {
private String name;
public static int count;
//Class initializer
static {
User.count = 0;
System.out.println("Class initializer execution\n↓");
}
//Instance initializer
{
System.out.println("Instance initializer execution\n↓");
}
//Constructor
public User(String name) {
this.name = name;
User.count++;
System.out.println("Constructor execution\n↓");
}
//Class method
public static void getInfo() {
System.out.println(User.count + "Instantiated times\n↓");
}
}
public class MyApp {
public static void main(String[] args) {
User.getInfo();
User ryo = new User("ryo");
User.getInfo();
User yu = new User("yu");
User.getInfo();
}
}
Execution result
$ java Myapp
Class initializer execution
↓
Instantiated 0 times
↓
Instance initializer execution
↓
Constructor execution
↓
Instantiated once
↓
Instance initializer execution
↓
Constructor execution
↓
Instantiated twice
↓
Recommended Posts