Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent of const(C++) in Java

Tags:

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?

like image 832
lowq Avatar asked Oct 25 '11 19:10

lowq


People also ask

What is the equivalent of const 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.

Is final in Java the same as const in C++?

Java final is equivalent to C++ const on primitive value types. With Java reference types, the final keyword is equivalent to a const pointer...

What is a const member function in Java?

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.

What is constant object in Java?

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.


1 Answers

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;     } } 
like image 74
mre Avatar answered Oct 21 '22 12:10

mre