"Constant" is an agreement between a programmer and himself. This convention can be more or less enforced by the compiler.
Instances of a class are "immutable" if they do not change during the normal course of application code execution. In some cases, we know that they do not change because the code actually prohibits this; in other cases, this is only part of how we use the class. For example, the java.util.Date instance is formally changed (it has the setTime() method on it), but it is customary to process it as if it were unchanged; this is just a common convention that the Date.setTime() method should not be called.
As additional notes:
- Immutability is often considered in terms of "external characteristics." For example, Java
String documented as immutable (as Javadoc says). But if you look at the source code, you will see that the String instance contains a private field named hash , which may change over time: this is the cache for the value returned by hashCode() . We still say that String is immutable because the hash field is an internal optimization that has no effect visible from the outside. - When reflected, the most private instance fields can be changed (including those marked as
final ) if the programmer so desires. Not that it's a good idea: it may violate the assumptions used by other code fragments using the specified instance. As I said, immutability is an agreement: if a programmer wants to fight on his own, then it can, but it can have adverse side effects on performance ... - Most Java values ββare actually references. You must determine if the reference object is part of what you consider to be "instance content". In your class, you have a field that refers to an array of integers. If the contents of this array are changed later, do you think this violates the immutability of your
MyClass instance? There is no general answer to this question.
source share