静态成员变量是属于类的, 不是属于某一个对象

@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

 

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值