The Java field initialization first initializes the block, then constructs the method to assign the value, and the last field initial value is assigned.
When there is an inheritance relationship between multiple classes, creating a subclass object causes the parent class to initialize the execution of the block.
Please write your own sample code to verify the above conclusions. (Blog Job)
Package Text1;
Class Father {
public static int n=56;
}
Class Son extends Father
{
public static void Out ()
{
SYSTEM.OUT.PRINTLN (n);
}
}
public class Text {
public static void Main (String args[])
{
Son.out ();
}
}
Validation Initializeblockdemo Examples
Calling a non-static field in a static method with a non-static method
Using the class's static fields and constructors, we can track the number of objects created by a class. Write a class that can query it at any time "how many objects have you created?" ”。
Package count;
public class Count {
public static void Main (string[] args) {
Number A=new number ();
Number B=new number ();
SYSTEM.OUT.PRINTLN ("You have already created" + number.number+ "objects");
}
}
Class number
{
static int number;
Public number ()
{
number++;
}
int GetNumber ()
{
return number;
}
}
- Please run Teststaticinitializeblock.java example, observe the output and summarize the " execution order of static initialization blocks " .
Static initialization blocks are executed in normal initialization blocks, parameterless constructors, and with a parameter constructor, and static initialization blocks are executed in the order of the classes.
Static methods only allow access to static data, so how do you access the instance members of a class in a static method (that is, a field or method that does not have the static keyword attached)?
Please write code to verify your idea. (Posted to Blog
public class Search
{
private String name;
Public Search (String name)
{
This.name=name;
}
public static void Main (String args[])
{
Search S=new Search ("Li");
Search S2=new Search ("total");
S.ask (s);
S.ask (S2);
}
public static void Ask (Search s)
{
S.say ();
}
public void Say ()
{
SYSTEM.OUT.PRINTLN (name);
}
}
Java Classes and objects