java - 能够改变静态变量值

标签 java

<分区>

如以下链接所述Link

Static variables are initialized only once, at the start of the execution. These variables will be initialized first, before the initialization of any instance variables.
A single copy to be shared by all instances of the class.

但是我可以改变静态变量的值

class Test {
  static int a =10;
  public static void main(String args[])
  {
    a=20;
    System.out.println("rest of the code...");
    Test1 t= new Test1();
    t.m();
  }
}

public class Test1 {
    void m () 
     {
         System.out.println(Test.a);
     }
}

最佳答案

定义意味着变量将在类定义的上下文中仅一次初始化。 Id est,对于您示例中的类 Test,无论您为此类实例化的对象数量如何,它都只会初始化一次。

还要考虑到初始化与稍后更改变量值不同。

在评论中说明您的问题:

class Test {
    public static long staticAtr = System.currentTimeMillis();
    public long nonStaticAtr = System.currentTimeMillis();

    public static void main(String[] args) {

        Test t1 = new Test();
        Thread.sleep(100);
        Test t2 = new Test();
        System.out.println(t1.staticAtr);
        System.out.println(t1.nonStaticAtr);
        System.out.println(t2.staticAtr);
        System.out.println(t2.nonStaticAtr);
}

t1 和 t2 显示相同的 staticAtr,它在执行开始时只初始化一次,而 t1 和 t2 的 nonStaticAtr 在每个实例化时初始化一次,因此具有不同的值。

关于java - 能够改变静态变量值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49969290/

相关文章:

java - 从以字符开头的字符串中删除子字符串

java - 我的狗铁人三项计划出错

java - 我的 Firebase/Facebook Auth 登录有效,并且不会在我的下一个 Activity 中显示用户用户名 : activity_main. xml

java - 获取投球手计数以显示在 League RecyclerView 中

java - 带有外部代码的方法 (Java)

java - 将代码转换为多线程版本

java - 在 Jersey 中将 int 数组作为 @QueryParam 发送

java - Spring 中是否有任何插件或模块,如用于 Java 的 Django flatpages?

java - 我想在连接到 websocket 时显示加载动画

java - 如何为 "hot deployer/replacer"编写 hello world ?