Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the Java equivalent of C++'s const member function?

Tags:

java

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:

  1. Prevents overriding/polymorphing that method in a subclass.
  2. Makes that method inline-able. (see comment by @Joachim Sauer below)

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?

like image 317
ef2011 Avatar asked May 04 '11 16:05

ef2011


People also ask

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 the Java equivalent of const?

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 Java final same as C++ const?

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

Does Java have const?

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.


2 Answers

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:

  • the primitive wrappers 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.

like image 171
Joachim Sauer Avatar answered Sep 22 '22 01:09

Joachim Sauer


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.

like image 45
Erik Avatar answered Sep 24 '22 01:09

Erik