The Java equivalent of const
In a language such as C++, the const keyword can be used to force a variable
or pointer to be read-only or immutable.
This prevents it from being updated unintentially and can have advantages when it comes
to thread-safety.
Let us review briefly how const is used in a language such as C++ before considering
how to achieve the Java equivalent of const. As an example, suppose
that we have a struct declared
as follows:
typedef struct Obj {
int ival;
struct Obj *next;
} OBJ;
Ordinarily, if we declare a variable of type OBJ or as being a pointer to
an OBJ, there's nothing to stop us modifying the object's fields
via that variable after declaration.
However, if we declare either variable as const, then the fields
of the object cannot be modified via that variable:
const OBJ obj1;
const OBJ *obj2;
obj1.ival = 0; <-- NOT ALLOWED!
obj1.next = 0; <-- NOT ALLOWED!
obj2->ival = 0; <-- NOT ALLOWED!
obj2->next = 0; <-- NOT ALLOWED!
Note that there are some limitations, however:
- The const keyword doesn't really give us any guarantee about the modifiability
of the actual object, just about whether a particular variable gives
read-only accessl.
- The read-only guarantee isn't applied recursively to fields inside
the referred-to struct or object.
This means that we can create a new variable referring to the same struct that
removes the const operator, then use that variable to modify the struct. And
we can change obj2->next->next even if we can't change obj2->next.
So the following code is allowed:
const OBJ obj1;
const OBJ *obj2;
obj2->next->next = 0;
OBJ *objRef = (OBJ *) obj2;
objRef->next = 0;
Const pointers in C++
A subtlety is that by changing the order of the modifiers,
we can create a const pointer. In this case, the contents of the
struct can be modified (via this pointer variable),
but the actual pointer can't:
OBJ* const obj;
obj->next = 0; // Allowed
obj = otherPtr; // Not allowed
Const member functions
Finally, and perhaps less commonly, const can be used in C++ to indicate
that a member function of a class has no side effects on the
object it is applied to. (In effect, it is not allowed to modify any of the object's fields.)
const in Java
On the next page, we look at the equivalent of const in Java,
showing that in some cases the final keyword provides similar functionality. But we see that
in Java, access to object members is controlled by the class itself, so another workaround
must be provided for giving read-only access to object members.
If you enjoy this Java programming article, please share with friends and colleagues. Follow the author on Twitter for the latest news and rants.
Editorial page content written by Neil Coffey. Copyright © Javamex UK 2021. All rights reserved.