Re: Question regarding final blank variable initilisation
walidhaouari@hotmail.com wrote:
Plz can someone explain the difference between static final variable
and final instance variable
A static variable -- final or not -- is associated with
the class itself and not with any particular object of the
class. There is "one copy" of a static variable, no matter
how many of the class' objects exist (there is one copy even
if zero objects exist).
A non-static or "instance" variable -- final or not --
exists as part of an object created from the class. Every
object has its own version of the instance variable; there
are exactly as many "copies" of the instance variable as
there are objects of the class (if there are zero objects,
there are zero instance variables).
A final variable -- static or instance -- cannot have a
new value assigned to it after initialization. Since a static
variable is created when the class is loaded, a static final
must be initialized at that time and never changed afterwards.
The initialization can be written in the declaration
static final int THE_ANSWER = 42;
or can be performed by a static initialization block:
static final int THE_ANSWER;
static {
THE_ANSWER = 42;
}
An instance variable is created each time an object of the
class is created. A final instance variable must be initialized
at that time and never changed afterwards. The initialization
can be written in the declaration
final int theAnswer = 42;
or in a (non-static) initialization block
final int theAnswer;
{
theAnswer = 42;
}
or in each constructor:
final int theAnswer;
MyClass() {
theAnswer = 42;
}
MyClass(double trouble) {
theAnswer = (int)Math.round(trouble);
}
regarding their initilisation: in particular : I noticed that if we
leave a final INSTANCE variable non initialised, the code will compile
fine (unless we make a call to it) while it's not the case for a
static final variable.
That shouldn't be the case. Could you show a short, complete
code sample that demonstrates exactly what you see? I suspect
the variable *is* being initialized, perhaps non-obviously.
--
Eric Sosman
esosman@acm-dot-org.invalid