We always write:
public static final int A = 0;
Question:
- Is
static final
the only way to declare a constant in a class? - If I write
public final int A = 0;
instead, isA
still a constant or just an instance field? - What is an instance variable? What's the difference between an instance variable and an instance field?
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
typeIf you wish to change the value of the enum you have created, provide a mutator method.
Example of accessing:
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 havefinal
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 ,
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.