In the
Java programming language
Java is a high-level, class-based, object-oriented programming language that is designed to have as few implementation dependencies as possible. It is a general-purpose programming language intended to let programmers ''write once, run anywh ...
, the
final
keyword
Keyword may refer to:
Computing
* Keyword (Internet search), a word or phrase typically used by bloggers or online content creator to rank a web page on a particular topic
* Index term, a term used as a keyword to documents in an information syst ...
is used in several contexts to define an entity that can only be assigned once.
Once a
final
variable has been assigned, it always contains the same value. If a
final
variable holds a reference to an object, then the state of the object may be changed by operations on the object, but the variable will always refer to the same object (this property of
final
is called ''non-transitivity''). This applies also to arrays, because arrays are objects; if a
final
variable holds a reference to an array, then the components of the array may be changed by operations on the array, but the variable will always refer to the same array.
Final classes
A final
class
Class or The Class may refer to:
Common uses not otherwise categorized
* Class (biology), a taxonomic rank
* Class (knowledge representation), a collection of individuals or objects
* Class (philosophy), an analytical concept used differentl ...
cannot be subclassed. As doing this can confer security and efficiency benefits, many of the Java standard library classes are final, such as and .
Example:
public final class MyFinalClass
public class ThisIsWrong extends MyFinalClass // forbidden
Final methods
A final
method
Method ( grc, μέθοδος, methodos) literally means a pursuit of knowledge, investigation, mode of prosecuting such inquiry, or system. In recent centuries it more often means a prescribed process for completing a task. It may refer to:
*Scien ...
cannot be
overridden or hidden by subclasses. This is used to prevent unexpected behavior from a subclass altering a method that may be crucial to the function or consistency of the class.
Example:
public class Base
public class Derived extends Base
A common misconception is that declaring a method as
final
improves efficiency by allowing the compiler to directly insert the method wherever it is called (see
inline expansion
In computing, inline expansion, or inlining, is a manual or compiler optimization that replaces a function call site with the body of the called function. Inline expansion is similar to macro expansion, but occurs during compilation, without ch ...
). Because the method is loaded at
runtime, compilers are unable to do this. Only the runtime environment and
JIT
Jit (also known as jiti, jit-jive and the Harare beat) is a style of popular Zimbabwean dance music. It features a swift rhythm played on drums and accompanied by a guitar. Jit evolved out many diverse influences, including domestic chimurenga, ...
compiler know exactly which classes have been loaded, and so only they are able to make decisions about when to inline, whether or not the method is final.
Machine code compilers that generate directly executable, platform-specific
machine code
In computer programming, machine code is any low-level programming language, consisting of machine language instructions, which are used to control a computer's central processing unit (CPU). Each instruction causes the CPU to perform a very ...
, are an exception. When using
static linking
In computer science, a static library or statically-linked library is a set of routines, external functions and variables which are resolved in a caller at compile-time and copied into a target application by a compiler, linker, or binder, produci ...
, the compiler can safely assume that methods and variables computable at
compile-time
In computer science, compile time (or compile-time) describes the time window during which a computer program is compiled.
The term is used as an adjective to describe concepts related to the context of program compilation, as opposed to concept ...
may be inlined.
Final variables
A final
variable
Variable may refer to:
* Variable (computer science), a symbolic name associated with a value and whose associated value may be changed
* Variable (mathematics), a symbol that represents a quantity in a mathematical expression, as used in many ...
can only be initialized once, either via an initializer or an assignment statement. It does not need to be initialized at the point of declaration: this is called a "blank final" variable. A blank final
instance variable
In class-based, object-oriented programming, an instance variable is a variable defined in a class (i.e. a member variable), for which each instantiated object of the class has a separate copy, or instance. An instance variable has similarities ...
of a class must be definitely assigned in every constructor of the class in which it is declared; similarly, a blank final static variable must be definitely assigned in a static initializer of the class in which it is declared; otherwise, a compile-time error occurs in both cases. (Note: If the variable is a reference, this means that the variable cannot be re-bound to reference another object. But the object that it references is still
mutable
In object-oriented and functional programming, an immutable object (unchangeable object) is an object whose state cannot be modified after it is created.Goetz et al. ''Java Concurrency in Practice''. Addison Wesley Professional, 2006, Section 3 ...
, if it was originally mutable.)
Unlike the value of a
constant, the value of a final variable is not necessarily known at compile time. It is considered good practice to represent final constants in all uppercase, using underscore to separate words.
Example:
public class Sphere
Any attempt to reassign
radius
,
xPos
,
yPos
, or
zPos
will result in a compile error. In fact, even if the constructor doesn't set a final variable, attempting to set it outside the constructor will result in a compilation error.
To illustrate that finality doesn't guarantee immutability: suppose we replace the three position variables with a single one:
public final Position pos;
where
pos
is an object with three properties
pos.x
,
pos.y
and
pos.z
. Then
pos
cannot be assigned to, but the three properties can, unless they are final themselves.
Like full
immutability
In object-oriented and functional programming, an immutable object (unchangeable object) is an object whose state cannot be modified after it is created.Goetz et al. ''Java Concurrency in Practice''. Addison Wesley Professional, 2006, Section 3.4 ...
, the use of final variables has great advantages, especially in optimization. For instance,
Sphere
will probably have a function returning its volume; knowing that its radius is constant allows us to
memoize the computed volume. If we have relatively few
Sphere
s and we need their volumes very often, the performance gain might be substantial. Making the radius of a
Sphere
final
informs developers and compilers that this sort of optimization is possible in all code that uses
Sphere
s.
Though it appears to violate the
final
principle, the following is a legal statement:
for (final SomeObject obj : someList)
Since the obj variable goes out of scope with each iteration of the loop, it is actually redeclared each iteration, allowing the same token (i.e.
obj
) to be used to represent multiple variables.
Final variables in nested objects
Final variables can be used to construct trees of immutable objects. Once constructed, these objects are guaranteed not to change anymore. To achieve this, an immutable class must only have final fields, and these final fields may only have immutable types themselves. Java's primitive types are immutable, as are strings and several other classes.
If the above construction is violated by having an object in the tree that is not immutable, the expectation does not hold that anything reachable via the final variable is constant. For example, the following code defines a coordinate system whose origin should always be at (0, 0). The origin is implemented using a
java.awt.Point
though, and this class defines its fields as public and modifiable. This means that even when reaching the
origin
object over an access path with only final variables, that object can still be modified, as the below example code demonstrates.
import java.awt.Point;
public class FinalDemo
The reason for this is that declaring a variable final only means that this variable will point to the same object at any time. The object that the variable points to is not influenced by that final variable though. In the above example, the origin's x and y coordinates can be freely modified.
To prevent this undesirable situation, a common requirement is that all fields of an immutable object must be final, and that the types of these fields must be immutable themselves. This disqualifies
java.util.Date
and
java.awt.Point
and several other classes from being used in such immutable objects.
Final and inner classes
When an anonymous
inner class In object-oriented programming (OOP), an inner class or nested class is a class declared entirely within the body of another class or interface. It is distinguished from a subclass.
Overview
An instance of a normal or top-level class can exist on ...
is defined within the body of a method, all variables declared
final
in the scope of that method are accessible from within the inner class. For scalar values, once it has been assigned, the value of the
final
variable cannot change. For object values, the reference cannot change. This allows the Java compiler to "capture" the value of the variable at run-time and store a copy as a field in the inner class. Once the outer method has terminated and its
stack frame
In computer science, a call stack is a stack data structure that stores information about the active subroutines of a computer program. This kind of stack is also known as an execution stack, program stack, control stack, run-time stack, or mac ...
has been removed, the original variable is gone but the inner class's private copy persists in the class's own memory.
import javax.swing.*;
public class FooGUI
Blank final
The blank final, which was introduced in Java 1.1, is a final variable whose declaration lacks an initializer. Previous to Java 1.1, a final variable was required to have an initializer. A blank final, by definition of "final", can only be assigned once. i.e. it must be unassigned when an assignment occurs. In order to do this, a Java compiler runs a flow analysis to ensure that, for every assignment to a blank final variable, the variable is definitely unassigned before the assignment; otherwise a compile-time error occurs.
final boolean hasTwoDigits;
if (number >= 10 && number < 100)
if (number > -100 && number <= -10)
In addition, a blank final also has to be definitely assigned before being accessed.
final boolean isEven;
if (number % 2 0)
System.out.println(isEven); // compile-error because the variable was not assigned in the else-case.
Note though that a non-final local variable also needs to be definitely assigned before being accessed.
boolean isEven; // *not* final
if (number % 2 0)
System.out.println(isEven); // Same compile-error because the non-final variable was not assigned in the else-case.
C/C++ analog of final variables
In
C and
C++
C++ (pronounced "C plus plus") is a high-level general-purpose programming language created by Danish computer scientist Bjarne Stroustrup as an extension of the C programming language, or "C with Classes". The language has expanded significan ...
, the analogous construct is the
const
In some programming languages, const is a type qualifier (a keyword applied to a data type) that indicates that the data is read-only. While this can be used to declare constants, in the C family of languages differs from similar constructs i ...
keyword
Keyword may refer to:
Computing
* Keyword (Internet search), a word or phrase typically used by bloggers or online content creator to rank a web page on a particular topic
* Index term, a term used as a keyword to documents in an information syst ...
. This differs substantially from
final
in Java, most basically in being a
type qualifier In the C, C++, and D programming languages, a type qualifier is a keyword that is applied to a type, resulting in a ''qualified type.'' For example, const int is a qualified type representing a constant integer, while int is the corresponding u ...
:
const
is part of the ''
type,'' not only part of the identifier (variable). This also means that the constancy of a value can be changed by casting (explicit type conversion), in this case known as "const casting". Nonetheless, casting away constness and then modifying the object results in
undefined behavior
In computer programming, undefined behavior (UB) is the result of executing a program whose behavior is prescribed to be unpredictable, in the language specification to which the computer code adheres. This is different from unspecified behavior, ...
if the object was originally declared
const
. Java's
final
is a strict rule such that it is impossible to compile code that directly breaks or bypasses the final restrictions. Using
reflection Reflection or reflexion may refer to:
Science and technology
* Reflection (physics), a common wave phenomenon
** Specular reflection, reflection from a smooth surface
*** Mirror image, a reflection in a mirror or in water
** Signal reflection, in ...
, however, it is often possible to still modify final variables. This feature is mostly made use of when
deserializing objects with final members.
Further, because C and C++ expose pointers and references directly, there is a distinction between whether the pointer itself is constant, and whether the data pointed to by the pointer is constant. Applying
const
to a pointer itself, as in
SomeClass * const ptr
, means that the contents being referenced can be modified, but the reference itself cannot (without casting). This usage results in behaviour which mimics the behaviour of a
final
variable reference in Java. By contrast, when applying const to the referenced data only, as in
const SomeClass * ptr
, the contents cannot be modified (without casting), but the reference itself can. Both the reference and the contents being referenced can be declared as
const
.
C# analogs for final keyword
C# can be considered as similar to Java, in terms of its language features and basic syntax: Java has JVM, C# has .Net Framework; Java has bytecode, C# has MSIL; Java has no pointers (real memory) support, C# is the same.
Regarding the final keyword, C# has two related keywords:
# The equivalent keyword for methods and classes is
sealed
# The equivalent keyword for variables is
readonly
What is the equivalent of Java's final in C#?
/ref>
Note that a key difference between the C/C++ derived keyword const
and the C# keyword readonly
is that const
is evaluated at compile time, while readonly
is evaluated at runtime, and thus can have an expression that is only calculated and fixed later (at runtime).
References
{{reflist
Java (programming language)
Articles with example Java code