I was wondering if there was an equivalent to c++'s const in Java. I understand the final keyword, but unfortunately I cannot use that to declare a functions return value final. Instead, it always ensures the function cannot be overridden, correct?
Basically, I want to make sure a given returned class cannot be modified and is read only. Is that possible in Java?
No
Java does not support the concept of constness as C/C++ use it.
The Java equivalent to this Foo class cannot be written.
However, Java has another approach, using interfaces.
Java's
final
keyword is more similar toFoo * const
than any other c++ concept. Note thatFoo const*
is very common and useful, whileFoo * const
is less so.Java does not support const-qualification of references to objects.
Workarounds include the following:
Immutable objects prevent modification by the recipient, but they also prevent modification through any reference. They are not equivalent to C++ const pointers/references.
Closest are read-only interface types. You could map a const-correct C++ class to two Java units, one an interface with only the const-qualified methods.
This is sometimes useful, to control what can modify an instance of the class. However, it's not done as frequently as in C++.
I think you want a immutable object. An object is considered immutable if its state cannot change after it is constructed.
To do that you need
do not provide any methods which can change the state of the object in any way - not just setXXX methods, but any method which can change state.
public final class SomeThing{
}
Java specifically discarded some features of C++, const is one of it. This conscious decision can be reflected by the fact that
const
is a reserved word in Java (but not used)The designers probably thought that the feature is really annoying and not really useful. I had that feeling when I was a C++ coder. Certain kind of static checking is just way too much.
Not directly, but one workaround is an immutable object.
Example -
The "final" keyword means const. But the use of final in java is much different than C++ Only fields or local variables can be final. A final class is not a const class but a sealed class that cannot be inherited. A final method is a sealed method, a method that cannot be overridden.
In C++ there is the concept of "const type" but in java you have only the concept of const field, const method (not-overridable) and const class (not-inheritable).