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
finalis very different to C++’sconst. 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: