Quote:
If a static final field has a mutable reference type, it can still be a constant field if the referenced object is immutable.
I'm not sure what this mean; can someone give an example of that?
An example that Josh is talking about would be List, which is a mutable type (add(), remove(), etc), but you can assign an immutable instance to it:
public static final List<String> NAMES = Collections.unmodifiableList( Arrays.asList("foo", "bar")); // immutable
By the way, a great example of something that looks like a constant, but isn't, is a Date constant:
public static final Date EPOCH = new Date(0);
but then some code can do this:
EPOCH.setTime(123456789); // oops!
Date is mutable! Everyone will see such a change.
In constrast with this is something like String, which is immutable:
public static final String NAME = "Agent Smith"; // immutable
You can have a mutable type with an immutable subtype:
class Mutable {} // Not immutable, because it can be extended.
final class Immutable extends Mutable {}
// Reference type is mutable, but referenced object is immutable.
static final Mutable CONSTANT = new Immutable();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With