Initialization blocks: Initialization of the execution sequence during class instantiation is the execution of the static initialization block, then the normal initialization block, the last execution of the constructor, and the static initialization only for the first time
Executed and executed only once when instantiated.
public class HelloWorld {
String name; Declaring variable name
String sex; Declaring variables Sex
static int age;//declares a statically variable age
Construction method
Public HelloWorld () {
SYSTEM.OUT.PRINTLN ("Initialize name by construction method");
Name = "Tom";
}
Initialize block
{
SYSTEM.OUT.PRINTLN ("Initialize sex by ordinary initialization block");
Sex = "male";
}
Static initialization blocks
static {
SYSTEM.OUT.PRINTLN ("Initialize age by static initialization block");
Age = 20;
}
public void Show () {
System.out.println ("Name:" + name + ", Gender:" + Sex + ", Age:" + ages ");
}
public static void Main (string[] args) {
Creating objects
HelloWorld Hello = new HelloWorld ();
Call the Show method of an object
Hello.show ();
HelloWorld hello1=new HelloWorld ();
Hello1.show ();
}
}
Execution Result:
Initializing the age with static initialization blocks
Initialize sex with normal initialization blocks
Initialize name by constructing method
Name: Tom, Sex: Male, Age: 20
Initialize sex with normal initialization blocks
Initialize name by constructing method
Name: Tom, Sex: Male, Age: 20
Initialization program block for Java