Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Definition of a constant field in Bloch's Effective Java 2nd edition

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?

like image 820
traveh Avatar asked Oct 20 '25 12:10

traveh


2 Answers

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
like image 110
Bohemian Avatar answered Oct 23 '25 00:10

Bohemian


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();
like image 31
Andy Turner Avatar answered Oct 23 '25 02:10

Andy Turner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!