In C++, I can define an accessor member function that returns the value of (or reference to) a private data member, such that the caller cannot modify that private data member in any way.
Is there a way to do this in Java?
If so, how?
I know about the final
keyword but AFAIK, when applied to a method it:
But it doesn't restrict the method from returning a reference to a data member so that it can't modified by the caller.
Have I overlooked something obvious?
The const member functions are the functions which are declared as constant in the program. The object called by these functions cannot be modified. It is recommended to use const keyword so that accidental changes to object are avoided. A const member function can be called by any type of object.
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.
Java final is equivalent to C++ const on primitive value types. With Java reference types, the final keyword is equivalent to a const pointer...
Java doesn't have built-in support for constants. A constant can make our program more easily read and understood by others. In addition, a constant is cached by the JVM as well as our application, so using a constant can improve performance.
There's no equivalent to the C const
"type modifier" in Java (sadly).
The closest you can get is to return an immutable object or an immutable wrapper around a mutable object.
Immutability is not a language feature of Java, however, so you'll have to rely on Libraries.
Examples of immutable objects are:
Integer
, Character
, ..String
File
URL
Commonly used immutable wrapper (i.e. wrappers around mutable types that prevent mutation) are those returned by the Collecton.unmodifiable*()
methods.
This does not exist in java. final
and const
have different semantics, except when applied to a variable of a primitive type. The java solution typically involves creating immutable classes - where objects are initialized in construction and provide no accessors allowing change. Example of such classes would be e.g. String
or Integer
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With