Const-correctness - final in Java

final in Java

In Java, the qualifier final states that the affected data member or variable is not assignable, as below:

final int i = 3; i = 4; // Error! Cannot modify a "final" object

It must be decidable by the compilers where the variable with the final marker is initialized, and it must be performed only once, or the class will not compile. Java's final and C++'s const keywords have the same meaning when applied with primitive variables.

const int i = 3; // C++ declaration i = 4; // Error!

Considering pointers, a final reference in Java means something similar to const pointer in C++. In C++, one can declare a "const pointer type".

Foo *const bar = mem_location; // const pointer type

Here, bar must be initialised at the time of declaration and cannot be changed again, but what it points is modifiable. I.e. *bar = value is valid. It just can't point to another location. Final reference in Java work the same way except it can be declared uninitialized.

final Foo i; // a Java declaration

Note: Java doesn't support pointers.

One can also declare a "read-only" pointer in C++.

const Foo *bar;

Here bar can be modified to point anything, anytime; just that its value cannot be modified through bar. There is no equivalent mechanism in Java. Thus there are also no const methods. Const-correctness cannot be enforced in Java, although by use of interfaces and defining a read-only interface to the class and passing this around, one can ensure that objects can be passed around the system in a way that they cannot be modified. Java collections framework provides a way to create unmodifiable wrapper of a Collection via Collections.unmodifiableCollection and similar methods.

Methods in Java can be declared "final", but that has a completely unrelated meaning - it means that the method cannot be overridden in subclasses.

Interestingly, the Java language specification regards const as a reserved keyword — i.e., one that cannot be used as variable identifier — but assigns no semantics to it. It is thought that the reservation of the keyword occurred to allow for an extension of the Java language to include C++-style const methods and pointer to const type. An enhancement request ticket for implementing const correctness exists in the Java Community Process, but was closed in 2005 on the basis that it was impossible to implement in a backwards-compatible fashion.

Read more about this topic:  Const-correctness