In Java code, when new objects are created, an object with a zero-value property is then initialized:
"' Java
public class Test {
Private Date date = new Date ();
public static void Main (string[] args) throws Interruptedexception {
Test T = new Test ();
for (int i = 0; i < 5; i++) {
Thread.Sleep (1000);
System.out.println (T.date.tostring ());
}
}
}
```
The code runs the result:
"' Bash
Tue June 15:56:46 CST 2018
Tue June 15:56:46 CST 2018
Tue June 15:56:46 CST 2018
Tue June 15:56:46 CST 2018
Tue June 15:56:46 CST 2018
```
That is, when you create the object T of the test class, its Date property is initialized to the current time, and the subsequent call to the Date property gets a fixed value. If you create an object of the test class again, the Date property changes:
"' Java
public class Test {
Private Date date = new Date ();
public static void Main (string[] args) throws Interruptedexception {
Test T = new Test ();
for (int i = 0; i < 5; i++) {
System.out.println (T.date.tostring ());
}
System.out.println ("--------------------------------------------");
Thread.Sleep (1000);
t = new Test ();
for (int i = 0; i < 5; i++) {
System.out.println (T.date.tostring ());
}
}
}
```
The code runs the result:
"' Bash
Tue June 16:02:25 CST 2018
Tue June 16:02:25 CST 2018
Tue June 16:02:25 CST 2018
Tue June 16:02:25 CST 2018
Tue June 16:02:25 CST 2018
--------------------------------------------
Tue June 16:02:26 CST 2018
Tue June 16:02:26 CST 2018
Tue June 16:02:26 CST 2018
Tue June 16:02:26 CST 2018
Tue June 16:02:26 CST 2018
```
If you set the Date property to static, the date property will not change even if you create the object of the test class again:
"' Java
public class Test {
private static Date date = new Date ();
public static void Main (string[] args) throws Interruptedexception {
Test T = new Test ();
for (int i = 0; i < 5; i++) {
System.out.println (T.date.tostring ());
}
System.out.println ("--------------------------------------------");
Thread.Sleep (1000);
t = new Test ();
for (int i = 0; i < 5; i++) {
System.out.println (T.date.tostring ());
}
}
}
```
The code runs the result:
"' Bash
Tue June 16:07:41 CST 2018
Tue June 16:07:41 CST 2018
Tue June 16:07:41 CST 2018
Tue June 16:07:41 CST 2018
Tue June 16:07:41 CST 2018
--------------------------------------------
Tue June 16:07:41 CST 2018
Tue June 16:07:41 CST 2018
Tue June 16:07:41 CST 2018
Tue June 16:07:41 CST 2018
Tue June 16:07:41 CST 2018
```
Conclusion:
1. For the same object, its properties are initialized once, and if you just read this property, the property will not change;
2. If you create a different instance of a class, its property values may be different, and the property value is the same if it is static.
Initializing properties in Java object initialization from a piece of code