In C++ a getter & setter for a private data member is very useful due to the ability to control mutability via a const return value.
In Java, if I understand correctly (please correct me if I am mistaken), specifying final on a getter doesn’t work that way. Once the caller received the data member reference through the getter, it can modify it, despite it being private…
If that’s the case (and please correct me if I have a gross misconception here), why not declare the data member public and simplify things?
Making
immutablereturn values in java is a matter of either returning alreadyimmutableobjects types (such as String) or returning a copy for non-immutable objects.Sample 1 – Already immutable object
Sample 2 – Collection of already immutable objects
Sample 3 – Non-immutable object
Sample 4 – Collection of non-immutable objects
Sample 3 and 4 are for conveniance based on that the complex type implements the
Cloneableinterface.Furthermore, to avoid subclasses overriding your immutable methods you can declare them
final. As a side note, thebuilderpattern is typically useful for constructing immutable objects.