Thursday, March 12, 2009

is it necessary to initialize a final variable at the time of

Question :is it necessary to initialize a final variable at the time of
declaretion ? (CoreJava)

Answer :NO, it's not necessary.
Many text books say like this but thats not true. Value of a final variable
can be instance specific also, but in this case we have to initialise the
variable in all the constructors.
If we want to have a common final value of a variable for all the instances
then there are two ways.
1. Initialise the variable at class level (at the time of declaration) or 2. just
declare variable at class level and initialise it in any one of the instance
blocks i.e.
A. class A { final int a; {a=5;}}
B. class A { final int a = 5;}

No comments: