@Setter
@Getter
public class Insured extends Base implements Serializable {
private String time;
public static String staticTime;
{
String now = new Date().toLocaleString();
this.time=now;
}
static{
String now = new Date().toLocaleString();
Insured.staticTime=now;
}
}
public static void main(String[] args) throws InterruptedException {
Insured insured1 = new Insured();
System.out.println("time1:"+insured1.getTime());
System.out.println("staticTime1"+Insured.staticTime);
Thread.sleep(2000L);
Insured insured2 = new Insured();
System.out.println("time2:"+insured1.getTime());
System.out.println("staticTime2"+insured2.staticTime);
}
输出结果:
time1:2018-4-26 13:09:57
staticTime12018-4-26 13:09:57
time2:2018-4-26 13:09:59
staticTime22018-4-26 13:09:57
结论:
静态成员变量是属于类的,一旦赋值则不可改变, 所有对象共享这一个值. (平时使用需谨慎)
=========================分割线
非常感谢指点, 发现我原来对静态变量理解的是错误的. 贴上最新的理解
@Setter
@Getter
public class Insured{
public static String name = "hello";
public static void main(String[] args) throws Exception {
System.out.println(Insured.name); //初始值
Insured insured = new Insured();
insured.name = "town"; //通过对象来访问静态变量, 并赋值
System.out.println(Insured.name);//赋值后 用类名调用
System.out.println(insured.name);//赋值后 用对象调用
Insured insured2 = new Insured();
System.out.println(insured2.name); //用别的对象访问
}
}
//打印结果
hello
town
town
town