[ACCEPTED]-Constant Object vs Immutable Object-immutability
In fact, in Java the term constant has no defined 16 meaning. It occurs in the JLS only in the 15 larger term compile time constant expression, which is an expression which 14 can (and must) be calculated by the compiler 13 instead of at runtime. (And the keyword 12
const is reserved to allow compilers to give 11 better error messages.)
In Java, we instead 10 use the term final to refer to variables (whether 9 class, object or local ones) who can't be 8 changed, and immutable when we refer to objects who 7 can't change. Both can be used when speaking 6 about a variable
x - the first then means 5 the variable itself (meaning it can't be 4 switched to another object), the second 3 means the object behind the variable. Thus 2 here the two meanings are orthogonal, and 1 are often combined to create a "true constant".
I would read constant as being the same object (the 5 same reference), whereas immutable clearly means 4 to me the fact that the object doesn't change.
Since 3 these are two different things, I would 2 perhaps refer to this:
private final Immutable i = new Immutable();
as being a constant 1 immutable object.
Constant often has a very specific meaning 10 in different programming languages. In java, a 9 constant already refers to a constant variable, a 8 variable that cannot be changed after assignment, e.g.:
final int FOO = 1; FOO = 4; // constant variable cannot be changed.
An 7 immutable object is a constant object in 6 the sense that its properties can never 5 be changed, but of course an object pointed 4 to by a constant variable can still be changed. So 3 to avoid confusion, the term immutable (which 2 literally means "unchanging over time") is 1 used.
They are very close in meaning, with the 17 understanding that an Object contains methods 16 while a Constant is generally considered 15 to only contain data.
Within Java, there's 14 the additional consideration of the keyword 13
final, which basically means non-reassignable. Some 12 people will casually call a final variable 11 a constant (as it's reference to a particular 10 object is a constant. This often comes 9 about due to confusion as to the particular 8 roles of the member and the object it refers 7 to, as 95% of the time a person does this 6 to refer to an immutable Object.
Not every 5 method is to return back data that depends 4 wholly upon the internal members. For example 3
System.currentTimeMillis() returns back a Unix like timestamp, yet 2 there would be no need for the actual "System" object 1 to change.
More Related questions