java - Java中的最终变量是否需要使用“静态”关键字?
问题描述
我对 Java 中的final
andstatic
关键字感到困惑,我需要澄清以下问题:
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;
解决方案
static
并且final
是不同的概念。成员属于类static
而不是实例,而您不能重新分配final
变量。
MyClass.myVariable = 5; //这个变化反映在两个实例中
myVariable
➡️被宣布是不可能的final
。
我可以更改最终和静态关键字的顺序,例如
公共静态最终 int ERROR_CODE = 200; 或者
公共最终静态 int ERROR_CODE = 200;
➡️ 是的。它没有任何区别。
推荐阅读
- swift - 可以直接使用 Publisher 作为 SwiftUI 中的 @ObjectBinding 属性吗?
- android - Gradle:任务“:app:transformClassesWithMultidexlistForDebug”执行失败
- python - 如何在 python 中使用格式化创建自定义 Kivy 标签类?
- node.js - NodeJS:如何将所有传入的服务器请求记录到 mongodb?
- reactjs - 未捕获的 ReferenceError:未定义进程 - React-Rails
- debugging - 我可以告诉 valgrind 在将来访问特定范围的内存时警告我吗?
- image - 如何在 scikit-learn 中对不同大小和格式的不同图像进行分类?
- python - 如何按名称访问 numpy 数组列?
- json - 如何使 QuerySet JSON 可序列化?
- r - 如何从列表列表中检索元素及其所在的列表?