• Post Reply Bookmark Topic Watch Topic
  • New Topic

Constant final static vs final variable and Enum  RSS feed

 
Luca Olivieri
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi guys,

someone can tell me the difference between a final static variable (CONSTANT) and a final variable. I know that
the initialization can be different but  are logically the same?

A final variable can be considered like a constant? 

Intead in an Enum like this:



GOLDEN is a constant or is simplly a final variable?

Thank you very much i hope to be clear.

Luca
 
Campbell Ritchie
Marshal
Posts: 56530
172
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Neither final variables nor final static variables are constants. They are only constants if they have a set value which does not change.
public static final double ABSOLUTE_ZERO = -273.15; // Degrees Celsius
It is worth making a constant static so there will only be one copy of it.
final List<XYZ> xyzList;
The above List is not a constant. Its value is not fixed at the start of the program, and once the List has been initialised, its contents can change. It will point to the same List throughout, but (not being static) a different List for each object. Unless you take special measures, the List can always be changed:-Even if the identity of the List cannot be changed, its state can easily be changed, and how can an object which changes state be called constant?
 
Campbell Ritchie
Marshal
Posts: 56530
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please don't confuse enum and Enum. Both exist, and your example is both an enum and an Enum. I prefer the longer name, enumerated type.

In the case of an element in an enum, it can never change its identity. Even if you serialise and deserialise an object containing an enum element, that enum element will always occupy the same heap space location. It is therefore always the same instance. Read more about enumerated types in the Java® Language Specification (=JLS) and the Java™ Tutorials. Beware: the JLS can be very difficult to read, but I think that section is one of the easier to understand. It is a design principle that enumerated type elements shou‍ld be immutable, even though you wil have seen examples with fields and methods. If an enum element is immutable, then is constitutes a constant. You will even see the JLS calls it a constant.

[edit]The Planets example in the Java™ tutorials link has all its elements immutable; the mass and radius fields are initialised in the constructor and there are no methods that can change them. When I first leant enumerated types, that enum was bigger; it included PLUTO.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!