-Initialize with ** constructor ** -** Instance variable ** is initialized at ** instance creation **
** Constant (final) ** can also be ** initialized with the constructor ** Uninitialized constants defined in the class can be initialized in the constructor
Example)
public class Main{
public static void main(String[] args){
Sample a = new Sample(5);
System.out.println(a.num); //Is displayed as 5
}
}
class Sample{
final int num; //The constant field is not initialized at this point
Sample(int num){ //int num is a local variable with the same name as the instance variable
this.num = num; //Initialize constants in constructor
}
}
-Use an initializer (instance initializer) called {} --If there are multiple constructors overloaded, common processing can be performed first in the instance initializer. --The instance initializer runs ** just before it is instantiated **
Example)
public class Main{
public static void main(String[] args){
Sample a = new Sample(5); //"Run Instance Initializer"
System.out.println(a.num); //5
Sample b = new Sample(); //"Run Instance Initializer"
System.out.println(b.num); //10
}
}
class Sample{
final int num; //The constant field is not initialized at this point
{
System.out.println("Run Instance Initializer");
}
Sample(){
this.num = 10;
}
Sample(int num){
this.num = num; //Initialize constants in constructor
}
}
Static fields can be used without instantiating. Therefore, ** cannot be initialized by the constructor **
→ It is necessary to initialize with a static initializer (initializer)
Example)
public class Main{
public static void main(String[] args){
System.out.println(Sample.num); //100 and output
}
}
class Sample{
static final int num; //Static constants have not been initialized at this point
static {
num = 100; //Initialization of static constants
}
}
** Initializer-> Instance Initializer-> Constructor **
Example)
public class Main{
public static void main(String[] args){
User a = new User(); //Output "Execution of initializer, execution of instance initializer, execution of constructor"
}
}
class User{
private static int count;
static{
User.count = 0; //Initialize static variables
System.out.println("Run initializer");
}
{
System.out.println("Run Instance Initializer");
}
User(){
System.out.println("Executing the constructor");
}
}
Recommended Posts