Fields in the Java platform are generally divided into two types: class variables and object variables.
Class 1 variables
Usually modified by static, there are two types of initialization: code blocks and the use of private static methods:
The advantage of the private static method is that it can be reused when you need to reinitialize the variable.
A static initialization code block, like a normal block of code, closed with curly braces {}, preceded by a static keyword, a class can have any number of static initial blocks, and can appear anywhere in the class body. The operating system guarantees that the order of the static initial block calls is consistent with the order in which the source code appears.
Class 2 variables
There are also two types of initialization: Initialize the block final method.
The initialization code block for the instance variable is similar to the static initialization code block, but there is no static keyword.
A final method cannot be overridden by subclasses, which is particularly useful if the subclass is to reuse initialization code, which is set to final, because invoking a non-final method can cause problems when the instance is initialized.
For example:
classinitializeblockclass{{field= 200; } //Initialize block Public intfield = 100; PublicInitializeblockclass (intvalue) { This. field =value; } PublicInitializeblockclass () {}} Public classInitializeblock { Public Static voidMain (string[] args) {Initializeblockclass obj=NewInitializeblockclass (); System.out.println (Obj.field); Obj=NewInitializeblockclass (300); System.out.println (Obj.field); }}
The result is:
Java field Initialization