Java Reference
In-Depth Information
final Instance Variables
You can declare an instance variable
final
and blank
final
. An instance variable is a part of an object's state.
A
final
instance variable specifies part of the object's state that does not change after the object is created. A blank
final
instance variable must be initialized when an object is created. The following rules apply for initializing a
blank
final
instance variable:
•
It must be initialized in one of the instance initializers or all constructors. The following rules
expand on this rule.
•
If it is initialized in an instance initializer, it should not be initialized again in any other
instance initializers or constructors.
•
If it is not initialized in any of the instance initializers, the compiler makes sure it is initialized
only once, when any of the constructors is invoked. This rule can be broken into two sub-rules.
As a rule of thumb, a blank
final
instance must be initialized in all constructors. If you follow
this rule, a blank
final
instance variable will be initialized multiple times if a constructor
calls another constructor. To avoid multiple initialization of a blank
final
instance variable, it
should not be initialized in a constructor if the first call in the constructor is a call to another
constructor, which initializes the blank
final
instance variable.
The above rules for initializing a blank final instance variable may seem complex. However, it is simple to
understand if you remember only one rule that a blank
final
instance variable must be initialized once and only
once when any of the constructors of the class is invoked. All of the above-described rules are to ensure that this rule
is followed.
Let's consider different scenarios of initializing
final
and blank
final
instance variables. We do not have
anything to discuss about
final
instance variable as follows where
x
is a
final
instance variable for the
Test
class:
public class Test {
private final int x = 10;
}
The
final
instance variable
x
has been initialized at the time of its declaration and its value cannot be changed
afterwards.
The following code shows a
Test2
class with a blank
final
instance variable
y
:
public class Test2 {
private final int y; // A blank final instance variable
}
Attempting to compile the
Test2
class generates an error because the blank
final
instance variable
y
is never
initialized. Note that the compiler will add a default constructor for the
Test2
class, but it will not initialize
y
inside the
constructor. The following code for the
Test2
class will compile because it initializes
y
in an instance initializer:
public class Test2 {
private final int y;
{
y = 10; // Initialized in an instance initializer
}
}