JaVa
   

Constants

Constants are values that are declared with an initial value and cannot be altered thereafter. The standard naming convention for constants is for the variable name to be all in capital letters with multiple words being separated by an underscore character (_). Declaring constants is very simple. Here we use a new keyword, final, to create a constant variable.

static final byte MAX_DAILY_HOURS = 24;


The static keyword is used with the final keyword because you may not require multiple instances of a constant variable when you create multiple objects of the class to which the constant attribute belongs, as they will only share the same unchangeable value anyway. However, you can declare a constant with the keyword final alone (omitting the keyword static). The advantage of this lies in not specifying the value of the constant immediately.

final byte MAX_DAILY_HOURS;


The value of MAX_DAILY_HOURS must now be assigned a value in every constructor that is defined in the class to which it belongs; the value must be assigned once and only once and will then stay and cannot be changed from then on. This is useful if you want each object to have its own copy of a constant variable, with each constant being set to its own unique value in the constructor(s).

NoteĀ 

A final value cannot be initialized in any other method; it must be initialized either at the declaration point or in all of the constructors of the class to which it belongs. It must be implemented in all of the constructors because any one, but only one, of them could be used when creating the object where the constant must be initialized.

JaVa
   
Comments