在java代码中,当new一个对象的时候,先是创建了一个属性为零值的对象,然后进行初始化:
```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());
}
}
}
```
该代码运行结果:
```bash
Tue Jun 05 15:56:46 CST 2018
Tue Jun 05 15:56:46 CST 2018
Tue Jun 05 15:56:46 CST 2018
Tue Jun 05 15:56:46 CST 2018
Tue Jun 05 15:56:46 CST 2018
```
也就是说在创建Test类的对象t的时候,其date属性被初始化成当前时间,后续再调用date属性的时候会得到固定的值。而如果再次创建Test类的对象,则date属性会发生变化:
```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());
}
}
}
```
该代码运行结果:
```bash
Tue Jun 05 16:02:25 CST 2018
Tue Jun 05 16:02:25 CST 2018
Tue Jun 05 16:02:25 CST 2018
Tue Jun 05 16:02:25 CST 2018
Tue Jun 05 16:02:25 CST 2018
--------------------------------------------
Tue Jun 05 16:02:26 CST 2018
Tue Jun 05 16:02:26 CST 2018
Tue Jun 05 16:02:26 CST 2018
Tue Jun 05 16:02:26 CST 2018
Tue Jun 05 16:02:26 CST 2018
```
而如果将date属性设置为static的话,则即使再次创建Test类的对象, date属性也不会发生变化:
```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());
}
}
}
```
该代码运行结果:
```bash
Tue Jun 05 16:07:41 CST 2018
Tue Jun 05 16:07:41 CST 2018
Tue Jun 05 16:07:41 CST 2018
Tue Jun 05 16:07:41 CST 2018
Tue Jun 05 16:07:41 CST 2018
--------------------------------------------
Tue Jun 05 16:07:41 CST 2018
Tue Jun 05 16:07:41 CST 2018
Tue Jun 05 16:07:41 CST 2018
Tue Jun 05 16:07:41 CST 2018
Tue Jun 05 16:07:41 CST 2018
```
结论:
1. 针对同一个对象,其属性会初始化一次,如果只是读取这个属性,这个属性不会发生变化;
2. 如果创建一个类的不同实例,其属性值有可能不同,而如果属性值是static的话则是相同的。
原文地址:https://www.cnblogs.com/cord/p/9226681.html