Constant Values ​​in Java

I come from a C ++ background and wonder about the immutable Java features. Is it possible to return function values ​​as const? (this means that the return value cannot be changed)

Also for bonus points in C ++, a function definition can be postfix as const, to declare that the function will not change the class level values. Is this also possible in Java? (which means that a function by definition will not be able to change its state of the class inside)

Many thanks!

+6
source share
3 answers

No, Java final very different from C ++ const . You cannot complete any of the tasks.

To make an object immutable, you more or less need to ensure its execution (as opposed to attracting compiler 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 ....

  • Do not provide setter methods - methods that modify fields or objects referenced by fields.
  • Make all fields final and private .
  • Do not let subclasses override methods. The easiest way to do this is to declare the class as final . A more complex approach is to create a private constructor and build instances in factory methods.
  • If instance fields include references to mutable objects, do not allow these objects to be modified:
    • Do not provide methods that modify mutable objects.
    • Do not use references to mutable objects. Never store references to external, mutable objects passed to the constructor; if you need to create copies and store links to copies. Similarly, create copies of your internal mutable objects if you need to avoid returning originals to your methods.
+6
source

No, there really is no way to create immutable objects from anywhere. If you want something immutable, it must be immutable (final) throughout the tree.

eg. The following example uses final in all places (except 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); } } 
+1
source

I think you can return a copy of the object data for reading and, therefore, protect them from modification. But the extra copy seems to be a great price for immutability.

0
source

Source: https://habr.com/ru/post/914429/


All Articles