如何在 Java 中声明一个常量?

我们总是写:

public static final int A = 0;

问题:

  1. 在类中声明 不变的唯一方法是 static final吗?
  2. 如果我改写为 public final int A = 0;,那么 A仍然是 不变还是仅仅是 实例字段
  3. 什么是 实例变量? 实例变量实例字段有什么区别?
302021 次浏览

Anything that is static is in the class level. You don't have to create instance to access static fields/method. Static variable will be created once when class is loaded.

Instance variables are the variable associated with the object which means that instance variables are created for each object you create. All objects will have separate copy of instance variable for themselves.

In your case, when you declared it as static final, that is only one copy of variable. If you change it from multiple instance, the same variable would be updated (however, you have final variable so it cannot be updated).

In second case, the final int a is also constant , however it is created every time you create an instance of the class where that variable is declared.

Have a look on this Java tutorial for better understanding ,

  1. You can use an enum type in Java 5 and onwards for the purpose you have described. It is type safe.
  2. A is an instance variable. (If it has the static modifier, then it becomes a static variable.) Constants just means the value doesn't change.
  3. Instance variables are data members belonging to the object and not the class. Instance variable = Instance field.

If you are talking about the difference between instance variable and class variable, instance variable exist per object created. While class variable has only one copy per class loader regardless of the number of objects created.

Java 5 and up enum type

public enum Color{
RED("Red"), GREEN("Green");


private Color(String color){
this.color = color;
}


private String color;


public String getColor(){
return this.color;
}


public String toString(){
return this.color;
}
}

If you wish to change the value of the enum you have created, provide a mutator method.

public enum Color{
RED("Red"), GREEN("Green");


private Color(String color){
this.color = color;
}


private String color;


public String getColor(){
return this.color;
}


public void setColor(String color){
this.color = color;
}


public String toString(){
return this.color;
}
}

Example of accessing:

public static void main(String args[]){
System.out.println(Color.RED.getColor());


// or


System.out.println(Color.GREEN);
}

final means that the value cannot be changed after initialization, that's what makes it a constant. static means that instead of having space allocated for the field in each object, only one instance is created for the class.

So, static final means only one instance of the variable no matter how many objects are created and the value of that variable can never change.