Alex Rivera | Logout

Equivalent of const(C++) in Java

Asked 2011-10-25T19:40:14.607
24

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?

Edit
Report

3 Answers

15

Java does not support const-qualification of references to objects.

Workarounds include the following:

  • Immutable objects.
  • Unmodifiable views of modifiable objects (for example, those returned by Collections.unmodifiable*()).
  • Read-only interface types
  • Defensive copies.

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++.

answered 2011-10-25T20:02:14.353
4

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).

answered 2011-10-25T19:44:25.250
0

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

  • ensure the class cannot be overridden - make the class final, or use static factories and keep constructors private
  • make fields private and final force callers to construct an object completely in a single step, instead of using a no-argument constructor combined with subsequent calls to setXXX methods
  • 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{

    public Something(String name) {
        fname=name
    }
    
    private final String fName;
    
    public String getName() {
          return fName;
    }
    

    }

answered 2011-10-25T19:45:26.420

Your Answer