Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Const return values in Java

Tags:

java

I'm coming from a C++ background and was wondering on the immutable features of Java. Can return values of functions be specified as const? (meaning the returned value cannot be modified)

Also for bonus points, in c++ a function definition can be postfix'ed as const to state that the function will not modify any class level values. Is this also possible in Java? (meaning that a function by definition will not be able to change it's class state internally)

Thanks so much!

like image 242
Jonathan Dunlap Avatar asked Apr 28 '12 20:04

Jonathan Dunlap


2 Answers

No, Java's final is very different to C++'s const. You cannot do either of the things you asked.

To make an object immutable, it's more or less up to you to enforce it (as opposed to enlisting the compiler's help as in C++). From http://docs.oracle.com/javase/tutorial/essential/concurrency/imstrat.html:

The following rules define a simple strategy for creating immutable objects. ...

  1. Don't provide "setter" methods — methods that modify fields or objects referred to by fields.
  2. Make all fields final and private.
  3. Don't allow subclasses to override methods. The simplest way to do this is to declare the class as final. A more sophisticated approach is to make the constructor private and construct instances in factory methods.
  4. If the instance fields include references to mutable objects, don't allow those objects to be changed:
    • Don't provide methods that modify the mutable objects.
    • Don't share references to the mutable objects. Never store references to external, mutable objects passed to the constructor; if necessary, create copies, and store references to the copies. Similarly, create copies of your internal mutable objects when necessary to avoid returning the originals in your methods.
like image 65
Oliver Charlesworth Avatar answered Oct 07 '22 00:10

Oliver Charlesworth


No, there is actually no way to create immutable objects out of anywhere. If you want something immutable, it has to be immutable (final) along the whole tree.

e.g. the following example uses final in every place (except of the root) but is still not able to prevent any changes:

public class justAnInt {
    public int a = 0;
    public int b = 0;
}

// -----------------------------------

public class AliasProblem{
    private final justAnInt var = new justAnInt();
    final justAnInt getVar()
    {
        return var;
    }

    public static void main(String argv[])
    {
        final AliasProblemObject = new AliasProblem();
        final justAnInt localVar = AliasProblemObject.getVar();
        localVar.a = 19;
        System.out.println("object: " + object.getVar().a);
        System.out.println("local: " + localVar.a);
    }

}
like image 36
TheTrowser Avatar answered Oct 07 '22 00:10

TheTrowser