Now look at this another example in which getter is not letting reference to actual object escape. It is returning a view of underlaying collection.Only the getField operation has changed
If you don't want fields to be modified using getter then
There is the keyword final in Java, but it does not do the same as const in C++.
See Const-correctness in Wikipedia:
There is no way to declare that you will not modify the object pointed to by a reference through that reference in Java. Thus there are also no const methods. Const-correctness cannot be enforced in Java, although by use of interfaces and defining a read-only interface to your class and passing this around, you have a means to ensure that you can pass your objects around the system in a way they cannot be modified.
Methods in Java can be declared "final", but that has a completely unrelated meaning - it means that the method cannot be overridden in subclasses.
Interestingly, the Java language specification regards const as a reserved keyword — i.e., one that cannot be used as variable identifier — but assigns no semantics to it. It is thought that the reservation of the keyword occurred to allow for an extension of the Java language to include C++-style const methods and pointer to const type. The enhancement request ticket in the Java Community Process for implementing const correctness in Java was closed in 2005, implying that const correctness will probably never find its way into the official Java specification.
The way to prevent private reference instance fields from being modified is to return a copy of the field. In the case of the method with a List return type above, try this method insteadNote the returned List will reflect any changes made in the original class.
For other mutable objects, a copy of the original field is useful; such classes should provide a copy constructor or implement a clone() method.
For things like String which are not mutable, or for primitives, there is no need for any special precautions.
Anything that cannot be modified can be returned directly. This includes primitives and immutable types (eg String)
Anything that can be modified should have either an immutable or defensive copy returned
int is a primitive, so return the int;
Integer is immutable, so return the Integer
Collections are mutable so return immutable copies
Dates are mutable, so return defensive copies eg return new Date(oldDate)
Question: did we manage to change the internal value?
(Note that people will always chime in and say that it is possible using reflection. While this is worth considering it is related it is more of a security topic than a beginner topic)