I'm not sure what the author means when he writes that a singleton static factory method can guarantee that no two equal instances exist. Well actually I do kind of understand that but I'm confused by the following text when he demonstrates the equals method vs the literal comparison operator: "a.equals(b) if and only if a==b."
I understand that the equals()
method actually compares the contents of an object while the literal ==
compares to see if they are the same object in memory. This is confusing because he goes on to say that the client can use the ==
instead of the .equals(object)
method. How so? Why would the client use the ==
comparator if they're guaranteed to only one object?
Could someone write me a short coded example to explain this more concretely?
The authors text is below:
The ability of static factory methods to return the same object from repeated invocations allows classes to maintain strict control over what instances exist at any time. Classes that do this are said to be instance-controlled. There are several reasons to write instance-controlled classes. Instance control allows a class to guarantee that it is a singleton (Item 3) or noninstantiable (Item 4). Also, it allows an immutable class (Item 15) to make the guarantee that no two equal instances exist: a.equals(b) if and only if a==b. If a class makes this guarantee, then its clients can use the == operator instead of the equals(Object) method, which may result in improved performance. Enum types (Item 30) provide this guarantee.