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!
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. ...
- Don't provide "setter" methods — methods that modify fields or objects referred to by fields.
- Make all fields
final
andprivate
.- 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 constructorprivate
and construct instances in factory methods.- 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.
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);
}
}
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