You must initialize a final variable once and only once. There are three ways to do that for an instance variable:
- in the constructor
- in an instance initialization block.
- when you declare it
Here is an example of all three:
public class X
{
private final int a;
private final int b;
private final int c = 10;
{
b = 20;
}
public X(final int val)
{
a = val;
}
}
In each case the code is run once when you call new X(...)
and there is no way to call any of those again, which satisfies the requirement of the initialization happening once and only once per instance.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…