4

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?

traveh
  • 2,700
  • 3
  • 27
  • 44
  • Effective Java. **Page 238** https://books.google.es/books?id=ka2VUBqHiWkC&pg=PA238&lpg=PA238&dq=%22static+final+field+has+a+mutable+reference+type%22&source=bl&ots=yZIfJew4P3&sig=tvjvW3oooSNxNRaGF57ru2VwL8c&hl=es&sa=X&ved=0ahUKEwi-1Z3S5P7LAhULVxoKHRIfCToQ6AEILTAC#v=onepage&q=%22static%20final%20field%20has%20a%20mutable%20reference%20type%22&f=false – Guillaume Barré Apr 08 '16 at 10:04

2 Answers2

7

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
Bohemian
  • 412,405
  • 93
  • 575
  • 722
2

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();
Andy Turner
  • 137,514
  • 11
  • 162
  • 243