Java – static initializer and instance initializer and constructor
•
Java
There is already an answer to this question: > use of initializers vs constructors in java8
Solution
The main difference between them is the order in which they are executed To illustrate, I will explain with an example:
public class SomeTest { static int staticVariable; int instanceVariable; // Static initialization block: static { System.out.println("Static initialization."); staticVariable = 5; } // Instance initialization block: { System.out.println("Instance initialization."); instanceVariable = 10; } // Constructor public Sometest() { System.out.println("Constructor executed."); } public static void main(String[] args) { new Sometest(); new Sometest(); } }
The output result is:
Static initalization. Instance initialization. Constructor executed. Instance initialization. Constructor executed.
Short words:
Once the class is loaded by the JVM, the static initialization block runs. > The instance initialization block runs before the constructor before instantiating one object at a time. > The constructor (obviously) runs each time an object is instantiated
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码