Let's take a look at these two examples, I think it will allow you to understand.
public class InstanceAndSataticInit { { System.out.println("Test string is (instance init): " + this.testString); } static{ System.out.println("Test string is (static init ): " + InstanceAndSataticInit.testStringStatic); } public static String testStringStatic="test"; public String testString="test"; public static void main(String args[]) { new InstanceAndSataticInit(); } }
Output:
Test string is (static init ): null Test string is (instance init): null
AND
public class InstanceAndSataticInitVariableFirst { public static String testStringStatic="test"; public String testString="test"; { System.out.println("Test string is (instance init): " + this.testString); } static{ System.out.println("Test string is (static init ): " + InstanceAndSataticInitVariableFirst.testStringStatic); } public static void main(String args[]) { new InstanceAndSataticInitVariableFirst(); } }
output:
Test string is (static init ): test Test string is (instance init): test
So you can say that the sequence is this.
A static variable will be created, but will not be initialized.
Static initialization will be performed in accordance with the specified sequence.
- A non-static variable will be created, but will not be initialized.
- Non-static initialization will be performed in accordance with this sequence.
In order, I mean appearing in the code.
I think these steps answer your two not working example StaticInitialisation and InstanceInitialisation2
But in the case of your second working InstanceInitialisation1 example, with the this keyword, you really help the compiler lose sight of the text hierarchy. The same thing happens in the case of static , when I call InstanceAndSataticInit.testStringStatic in my first InstanceAndSataticInit example
Saif Jun 15 '15 at 6:36 2015-06-15 06:36
source share