The final Keyword
The
final is a keyword. This is similar to const
keyword in other languages.
This keyword may not be used as identifiers i.e. you cannot declare a variable
or class with this name in your Java program.
In
the Java programming language, the keyword "final" is used with
different entity, which makes it unchangeable later. It is a modifier that
indicates that a class cannot be extended, a variable cannot be changed, and a
method cannot be overridden. We can have final methods, final classes, final
data members, final local variables and final parameters.
- variables: A variable declared with the
final
keyword cannot be modified by the program, once it has been initialized. It can only be assigned to once.
Unlike the constant value, the value of a final variable is not necessarily known at compile time. Final variable comes in mostly two important situations: to prevent accidental changes to method parameters, and with variables accessed by anonymous classes.
The syntax of declaring a final type variable is:
public final double radius = 126.45; public final int PI = 3.145; |
- methods:
A final method cannot be overridden by subclasses and not be hidden. This
technology prevents unexpected behavior from a subclass for altering a
method that may be crucial to the function of the class.
private and static methods are always implicitly final in Java, since they cannot be overridden.
The syntax of declaring a final type method is:
public class MyFinalClass {
public final void myFinalMethod()
{ ???...
????}
}
- classes:
A final class cannot be extended. A final class implicitly has all the
methods declared as final, but not necessarily the data members.
The syntax of declaring a final type method is:
public
final class MyFinalClass { ???.. .} |
final Fields
The
fields can also be declared as final
. This is not the same thing
as declaring a method or class to be final
. When
a field is declared final
,
it is a constant, which cannot be changed. It can be set once.