I'm currently diving deep (at least relative to my limited knowledge as a programmer) into Java using Joshua Bloch's Effective Java.
In Item 1 under Creating and Destroying Objects, he states to consider static factory methods instead of constructors. For example,
public static Boolean valueOf(boolean b) {
return b ? Boolean.TRUE : Boolean.FALSE;
}
His reasoning in this item is clear to me, except for the part where he states that using static factory methods "allows an immutable value class". He expands on this statement: "guarantees that no two equal instances exist: a.equals(b)
if and only if a == b
". He states this is because using static factory methods doesn't require the creation of a new object every time they're invoked. Ergo, this makes classes instance-controlled: "allows classes to maintain strict control over what instances exist at any time."
I understand what these statements mean individually but cannot make sense of how exactly it relates to using static factory methods instead of constructors.
I'd appreciate any comments on helping me understand the matter, preferably with an example. Thank you in advance.