We always write:
public static final int A = 0;
Question:
static final
the only way to declare a constant in a class? public final int A = 0;
instead, is A
still a constant or just an instance field? You use the Const statement to declare a constant and set its value. By declaring a constant, you assign a meaningful name to a value. Once a constant is declared, it cannot be modified or assigned a new value. You declare a constant within a procedure or in the declarations section of a module, class, or structure.
Constants are basically variables whose value can't change. In C/C++, the keyword const is used to declare these constant variables. In Java, you use the keyword final .
If a variable should have a fixed value that cannot be changed, you can use the const keyword. The const keyword declares the variable as "constant", which means that it is unchangeable and read-only.
A class constant is declared inside a class with the const keyword. Class constants are case-sensitive. However, it is recommended to name the constants in all uppercase letters.
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.
enum
type in Java 5 and onwards for the purpose you have described. It is type safe.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); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With