参考

  1. 《Java核心技术卷1》

简述

如果将一个字段定义为static,每个类只有一个这样的字段。而对于非静态的实例字段,每个对象都有自己的一个副本。

  • 类的静态字段是所有实例对象共享的。

代码

  1. 含有静态字段的类
package static_class_test;

import java.util.UUID;

/**
 * @Author 夏秋初
 * @Date 2021/12/4 20:57
 */
public class StaticTest {
    protected static Integer num = 0;
    protected String id = UUID.randomUUID().toString();
    public Integer getNum(){
        return StaticTest.num;
    }
    public void setNum(Integer num){
        StaticTest.num = num;
    }
    @Override
    public String toString(){
        return "id:"+id+" num:"+StaticTest.num;
    }
}
  1. 调用含有静态字段的类
package static_class_test;

/**
 * @Author 夏秋初
 * @Date 2021/12/4 21:00
 */
public class Main {
    public static void main(String[] args) {
        StaticTest staticTest1 = new StaticTest();
        StaticTest staticTest2 = new StaticTest();
        StaticTest staticTest3 = new StaticTest();

        // 默认值
        System.out.println(staticTest1.toString());
        System.out.println(staticTest2.toString());
        System.out.println(staticTest3.toString());
        // 修改后
        staticTest2.setNum(2);
        // 获取修改后的
        System.out.println(staticTest1.toString());
        System.out.println(staticTest2.toString());
        System.out.println(staticTest3.toString());
        // 再次修改
        staticTest2.setNum(5);
        // 获取修改后的
        System.out.println(staticTest1.toString());
        System.out.println(staticTest2.toString());
        System.out.println(staticTest3.toString());

    }
}

  1. 运行结果

【转载】Java 类 静态字段是共享给所有对象的

相关文章:

  • 2021-11-26
  • 2021-12-09
  • 2022-12-23
  • 2022-02-07
  • 2021-10-30
  • 2022-12-23
  • 2022-02-09
  • 2021-11-28
猜你喜欢
  • 2022-12-23
  • 2021-11-30
  • 2021-07-02
  • 2022-12-23
  • 2022-02-01
  • 2021-06-20
相关资源
相似解决方案