public class Initializeblockdemo {
/**
* @param args
*/
public static void Main (string[] args) {
Initializeblockclass obj=new Initializeblockclass ();
System.out.println (Obj.field);
Obj=new Initializeblockclass (300);
System.out.println (Obj.field);
}
}
Class initializeblockclass{
The following sentence affects the initial value of the Field field before and after the initialization block
public int field=100;
{
field=200;
}
public int field=100;
public initializeblockclass (int value) {
This.field=value;
}
Public Initializeblockclass () {
}
}
The result is 100 300; it is obvious that the initialization block of a class in Java will run first only once, and if the variable is assigned a value in the class, it will change the value of the variable, including the Call function assignment.
Package demo;
Public class In extends father{
Public Static void Main (string[] args) {
TODO auto-generated Method stub
In x;
x = new in ();
}
}
class father{
{
int i = 100;
System. out. println (i);
}
}
The result is 100 shows that when there is an inheritance relationship between multiple classes, creating a subclass object causes the parent class to initialize the block's execution
Package demo;
Public class in{
Static int n = 10;
Public Static void Main (string[] args) {
Stac s = new Stac ();
N = S.fuzhi ();
S.Output(n);
}
}
class stac{
int a = 20;
int Fuzhi () {
int x;
x = A;
return x;
}
Static void Output (int b) {
System. out. println (b);
}
}
Result is 20
Using static methods to access instance members of a class is to assign an instance variable of the class to a static variable and then output it with a static method.
Java Chapter III Hands-on brain