Java initializer story

What is an initializer?

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
	}
}

What is the difference between an instance initializer and a constructor?

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

Java initializer story
Java static story
Java generic story
Lombok's Java 9+ support story
[Java] Aizu Online Judge's story 2
[Java] Aizu Online Judge's story 1
Java
Java
C # and Java Overrides Story
[Java version] The story of serialization
A really scary (Java anti-pattern) story
Story of passing Java Gold SE8
[Java] Really scary switch statement story
Java learning (0)
Studying Java ―― 3
[Java] array
Java protected
[Java] Annotation
Story of paiza.jp [Java standard input solution]
[Java] Module
Java array
Studying Java ―― 9
Java scratch scratch
Java tips, tips
Java methods
Java method
java (constructor)
Java array
[Java] ArrayDeque
java (override)
java (method)
Java string
java (array)
Java serialization
java beginner 4
JAVA paid
Studying Java ―― 4
Java (set)
java shellsort
[Java] compareTo
Studying Java -5
JUnit story
java reflexes
java (interface)
Java memorandum
☾ Java / Collection
Java array
Studying Java ―― 1
[Java] Polymorphism
Studying Java # 0
Java review
Java features
[Java] Inheritance
Range story
FastScanner Java
Java features
Java memo
java (encapsulation)
Java inheritance
[Java] Overload
Java basics