首页 > 解决方案 > Java中的最终变量是否需要使用“静态”关键字?

问题描述

我对 Java 中的finalandstatic关键字感到困惑,我需要澄清以下问题:

1.对于变量,有没有必要使用static?例如:

public final int ERROR_CODE = 200;

我认为没有必要使用static如下所示。我错了吗?

public static final int ERROR_CODE = 200;

2.据我所知,静态对于方法,类来说是有意义的,可以在不创建实例的情况下使用它们。但是,在此静态方法中也使用static变量对于同时更改它们的值也很有意义:

public class MyClass {
    public static int myVariable = 0; 
}

//Now in some other code creating two instances of MyClass
//and altering the variable will affect all instances

MyClass instance1 = new MyClass();
MyClass instance2 = new MyClass();

MyClass.myVariable = 5;  //This change is reflected in both instances


3.我可以改变最终和静态关键字的顺序吗?例如

public static final int ERROR_CODE = 200; 

或者

public final static int ERROR_CODE = 200; 

标签: javavariablesstaticconstantsfinal

解决方案


static并且final是不同的概念。成员属于类static而不是实例,而您不能重新分配final变量。

MyClass.myVariable = 5; //这个变化反映在两个实例中

myVariable➡️被宣布是不可能的final

我可以更改最终和静态关键字的顺序,例如

公共静态最终 int ERROR_CODE = 200; 或者

公共最终静态 int ERROR_CODE = 200;

➡️ 是的。它没有任何区别。


推荐阅读