Definition of constant field in Bloch’s effective java version 2

quote:

I'm not sure what that means; Can anyone give an example?

Solution

An example Josh is talking about is list, which is a variable 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 good example of a constant that looks like a constant but is not a constant is the date constant:

public static final Date EPOCH = new Date(0);

But some code can do this:

EPOCH.setTime(123456789); // oops!

The date is variable! Everyone will see such a change

Similarly, like string, it is immutable:

public static final String NAME = "Agent Smith"; // immutable
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>