Java Reference
In-Depth Information
The final Keyword
The
final
keyword is used in many contexts in a Java program. It takes on different meanings in different contexts.
However, as its name suggests, its primary meaning is the same in all contexts. Its primary meaning is
The construct with which the final keyword is associated does not allow modifying or replacing its
original value or definition.
If you remember the primary meaning of the
final
keyword, it will help you understand its specialized meaning
in a specific context. The
final
keyword can be used in the following three contexts:
•
A variable declaration
•
A class declaration
•
In this section, you will discuss the use of the
final
keyword only in the context of a variable declaration. The
chapter on inheritance discusses its use in the context of class and method declarations in detail. In this section, I will
briefly describe its meaning in all three contexts.
If a variable is declared
final
, it can be assigned a value only once. That is, the value of a
final
variable cannot
be modified once it has been set. If a class is declared
final
, it cannot be extended (or subclassed). If a method is
declared
final
, it cannot be redefined (overridden or hidden) in the subclasses of the class that contains the method.
Let's discuss the use of the
final
keyword in a variable declaration. In this discussion, a variable declaration
means the declaration of a local variable, a formal parameter of a method/constructor, an instance variable, and a
class variable. To declare a variable as
final
, you need to use the
final
keyword in the variable's declaration. The
following snippet of code declares four
final
variables:
YES
,
NO
,
MSG
, and
act
:
A method declaration
final int YES = 1;
final int NO = 2;
final String MSG = "Good-bye";
final Account act = new Account();
You can set the value of a
final
variable only once. Attempting to set the value of a
final
variable the second
time will generate a compilation time error.
final int x = 10;
int y = 101 + x; // Reading x is ok
// A compilation time error. Cannot change value of the final variable x once it is set
x = 17;
There are two ways to initialize a
final
variable:
•
You can initialize it at the time of its declaration.
•
Until what time you can defer the initialization of a
final
variable depends on the variable type. However, you
must initialize the
final
variable before it is read for the first time.
If you do not initialize a
final
variable at the time of its declaration, such a variable is known as a blank
final variable.
You can defer its initialization until a later time.