> what is the sense of postpone initialisation of
> finals?
>
> final int COUNT;
>
> .. // do some stuff here
>
> COUNT = 1234;
>
> is there a situation where postpone initialisation is
> useful?
Well, if you want the value from a file or database then this would be useful, since you need to connect to the file or database first.
Class Example {
final int x;
public Example(int x) {
this.x = x;
}
}
For a local final variable the previously given reason is correct. Many code standards (including Sun's) state that you should always declare varaibles at the beginning of blocks. If you want to follow the standard, delayed initialization of finals is neccesary for the previous example.
ok friends i experimented a little bit and tell you what i found out:
class TestClass
{
static final int a;
static { a=1; }
final int b;
{ b=1; }
// TestClass() { b=1; } // another possibility
}
- nonlocal static final members can only be postpone initialized in static initialisation blocks
- nonlocal instance finals can be initialized either in a constructor or a instance initialisation block.
- no nonlocal final can be assigned to in a method.
but i see no use for postpone initialisation of LOCAL finals. is there a reason why this is allowed by the compiler?
> but i see no use for postpone initialisation of LOCAL
> finals. is there a reason why this is allowed by the
> compiler?
Probably for consistency and for the reason I have already mentioned. The compiler already checks to make sure a non-final local has been initialized anyway, so why not allow it?
it would be really stupid to declare a local final at the beginning of a block and then initialize it later. hey man this is a constant! it should be important to see the name and value together at declaration time.
final int count; // good to know its here. but what IS count?
// do stuff
// do more stuff
// even more stuff
// nobody will notice it...
count=array.length;
// foo
// working hard...
// do even more lots of stuff
int n=count; // huh? which count?
Your method may be complicated enough that the finals scope may still be outside that of the scope in which it's initialised.
public void X()
{
final int something;
try {
something = doSomething();
} catch(AScrewUpException e) {
something = defaultValue;
}
... now use something;
}
--
Talden