The Java Tutorials have been written for JDK 8.Java教程是为JDK 8编写的。Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available.本页中描述的示例和实践没有利用后续版本中引入的改进,并且可能使用不再可用的技术。See Java Language Changes for a summary of updated language features in Java SE 9 and subsequent releases.有关Java SE 9及其后续版本中更新的语言特性的摘要,请参阅Java语言更改。
See JDK Release Notes for information about new features, enhancements, and removed or deprecated options for all JDK releases.有关所有JDK版本的新功能、增强功能以及已删除或不推荐的选项的信息,请参阅JDK发行说明。
The following rules define a simple strategy for creating immutable objects. 以下规则定义了创建不可变对象的简单策略。Not all classes documented as "immutable" follow these rules. 并非所有记录为“不可变”的类都遵循这些规则。This does not necessarily mean the creators of these classes were sloppy they may have good reason for believing that instances of their classes never change after construction. 这并不一定意味着这些类的创建者很马虎他们可能有充分的理由相信他们的类的实例在构建之后永远不会改变。However, such strategies require sophisticated analysis and are not for beginners.然而,这些策略需要复杂的分析,不适合初学者。
final
and private
.final
字段和private
字段。final
. final
。private
and construct instances in factory methods.private
,并在工厂方法中构造实例。Applying this strategy to 将此策略应用于SynchronizedRGB
results in the following steps:SynchronizedRGB
将导致以下步骤:
set
, arbitrarily transforms the object, and has no place in an immutable version of the class. set
任意变换对象,在类的不变版本中没有位置。invert
, can be adapted by having it create a new object instead of modifying the existing one.invert
,它可以通过创建新对象而不是修改现有对象来进行调整。private
; they are further qualified as final
.private
;他们还获得了final
资格。final
.final
。After these changes, we have 在这些更改之后,我们有了ImmutableRGB
:ImmutableRGB
:
final public class ImmutableRGB { // Values must be between 0 and 255. final private int red; final private int green; final private int blue; final private String name; private void check(int red, int green, int blue) { if (red < 0 || red > 255 || green < 0 || green > 255 || blue < 0 || blue > 255) { throw new IllegalArgumentException(); } } public ImmutableRGB(int red, int green, int blue, String name) { check(red, green, blue); this.red = red; this.green = green; this.blue = blue; this.name = name; } public int getRGB() { return ((red << 16) | (green << 8) | blue); } public String getName() { return name; } public ImmutableRGB invert() { return new ImmutableRGB(255 - red, 255 - green, 255 - blue, "Inverse of " + name); } }