When I look at "Think in Java" Today, there is a problem: whether the constructor of the class will be called when a static function is called. Do not find the relevant content on the Internet, try to test the results.
1 Public classTest {2 PublicTest () {3System.out.println ("constructor");4 }5 Public Static voidprint () {6System.out.println ("Static");7 }8 Public Static voidMain (string[] args) {9 test.print ();Ten } One}
Results:
1 Static
As you can see, the result is only static, that is, the constructor is not executed.
At the beginning of this question, there is the initialization order, whether the static method is also initialized before the execution of it?
1 Packagetest;2 3 Public classTest {4 Static intI=1;5 PublicTest () {6System.out.println ("constructor");7 }8 Public Static voidprint () {9System.out.println (i+ "Static");Ten } One Public Static voidMain (string[] args) { A test.print (); - } -}
Results:
1 1static
As you can see, the static variables have been initialized.
By flipping the book, Initialize the order:
Static variables, static initialization blocks > variables, initialization blocks > constructors
It is important to note that static functions cannot invoke non-static variables, which are for instance. The first code also shows that the constructor is not called after the static function is called.
Whether the constructor is called when Java calls a static function