Today I encountered such a block of code, understand for a long time, now understand, give you some examples to see
Create one class first:
Package accp.com;
/**
* One of the classes
* @author Xuxiaohua
*
*/
public class One {
Public one (String str) {//Set a constructor
System.out.println (str);
}
}
Create a second class:
Package accp.com;
public class-{
One One=new one ("one1");
One One2=new one ("One2");
Static one one3=new ("One3");//Why this sentence only executes once, because the static block executes only once, when the Java virtual machine starts to load
Public A (String str) {
System.out.println (str);
}
}
Then write the test class:
Package accp.com;
public class Test {
Static, two, new ("two");//static blocks are the first way to go when Java is loaded, so this sentence is always the same, regardless of where it is placed.
public static void Main (String args[]) {
T=new ("Two2");
SYSTEM.OUT.PRINTLN ("Start Main method =========");
Tw=new ("Two3");
System.out.println ("Execution is complete. ");
}
}
The result of the operation is:
ONE3------Explanation: the static block executes first, so nature goes into two classes, and then there is static one One3=new one ("One3") in both classes; static, so go ahead and say it.
ONE1------Explanation: The test class, static two two = new second ("Two"), in the definition of two two, so go first to define the class two and then execute the method inside, note that there will be no one3, because the static block is only executed once
One2
The----explanation: Static---------------------------------------the preceding definition goes through new
ONE1---Explanation: two t=new two ("Two2"); like the above, the first half, two T is the definition of the variable, so walk the method in two, but do not execute the static block, because it is said that the static block is executed only once. Well, the first part of the definition is read, then the second half of the instantiation: New Two ("Two2"), instantiating the object, and outputting the TWO2
One2
Two2
Start the Main method =========//these words there is nothing to explain it!
ONE1------Explanation: The reason ditto
One2
Two3
Execution is complete.
In conclusion, you need to understand static blocks and constructors, as well as define and instantiate.
Two two;//this belongs in defining a variable
New ();//belongs to the instantiation of the object of the other, and the two=new of the object is defined and instantiated.
The second is the static block, the static block is only run once when Java is loaded, and is the code block that executes first.
Learn like riding, behind.
Java constructors, static block understanding of Java