Java misunderstanding: static code blocks will be automatically executed when classes are loaded ?, Java misunderstanding
Is the JAVA static code block automatically executed when the class is loaded?
Many Java developers have been deeply attacked by this idea for n times, and more people have been attacked by blogs that spread this wrong idea on the Internet.
Such as: http://blog.csdn.net/leeyu35/article/details/7755304
Then our program proves that this sentence is wrong:
Class MyClass1 {static {// static block System. out. println ("static block") ;}} public class Main {Class [] classArray = {MyClass1.class // to reference this class, the Class must be loaded into the virtual machine }; public static void main (String [] args) {System. out. println ("hello word ");}}
Execution Result: "static bolck" is not output"
When will the static block be called? I have found an article to describe more detailed blogs.
Http://www.cnblogs.com/ivanfu/archive/2012/02/12/2347817.html
When to execute Java static code blocks
This class will be executed when it is called or instantiated for the first time.
The static code block is executed only once. It is generally used to initialize some values and is globally shared among all objects.
Java static code block class loading sequence
The reason is one sentence: If you have a father, you will have a son!
When running the program, Load the AB class. Because A is A subclass of B, Load B first, and add it to class A LoadA. when calling the A = new A () code, will first call the constructor of the parent class B Create B and then call the constructor Create A of