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?
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...
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.
In java object constant means you cannot change its reference but you can change the values of its state variables untill they are not final. if all the member variables are final then its a perfect constant, where you cannot change anything.
Basically, I want to make sure a given returned class cannot be modified and is read only. Is that possible in Java?
Not directly, but one workaround is an immutable object.
Example -
public final Foo{ private final String s; public Foo(String s){ this.s = s; } // Only provide an accessor! public String getString(){ return s; } }
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