1. Sample program:
1 classInitializeblockclass2 {3 {4field=200;5 }6 Public intfield=100;7 PublicInitializeblockclass (intvalue) {8 This. field=value;9 }Ten PublicInitializeblockclass () { One A } - } - the Public classInitializeblockdemo { - Public Static voidMain (string[] args) { - -Initializeblockclass obj=NewInitializeblockclass (); + System.out.println (Obj.field); - +obj=NewInitializeblockclass (300); A System.out.println (Obj.field); at } - -}
2. Running Results
3. Results Analysis
(1)
{
field=200;
}
This section is the initialization block for the class, and you can enclose the statement in the class using "{" and "}", directly as a member of the class. This "No Name" member of the class is used to initialize the fields of the class.
(2)
public int field=100; Initialize when defined , at this time field = +;
(3)
System.out.println (Obj.field); Output field value of
(4)
Obj=new Initializeblockclass (300);
System.out.println (Obj.field);
Using the constructor method to initialize , The value of field is initialized to
the rule of initialization of the 4.Java field .
(1) The default value specified when executing the class member definition or the initialization block of the class, exactly which one you want to see is "in front".
(2) executes the constructor of the class.
Note: The initialization blocks of the class do not receive any parameters, and they are executed whenever an object of the class is created. Therefore, it is appropriate to encapsulate those "code that must be executed when the object is created."
Rules for initializing Java fields