【发布时间】:2021-08-04 02:44:40
【问题描述】:
我对 Java 中的 final 和 static 关键字感到困惑,需要澄清以下问题:
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;
【问题讨论】:
-
静态最终字段是属于该类的常量。非静态 final 字段在它所属的实例上是不可变的。
标签: java variables static constants final