Sub topic 7
Static factory methods
This chapter assumes you can write classes with private constructors and fields, you know what static means for a method, and you know a static method has no this. It builds on the static context rules from earlier chapters.
What a static factory method is
A static factory method is a static method that returns an instance of its class (or of a related type). Callers use it instead of calling new directly. The class usually makes its constructor private, so the factory methods become the only way to create objects.
public final class Temperature {
private final double celsius;
private Temperature(double celsius) {
this.celsius = celsius;
}
public static Temperature ofCelsius(double celsius) {
return new Temperature(celsius);
}
public static Temperature ofFahrenheit(double fahrenheit) {
return new Temperature((fahrenheit - 32) * 5 / 9);
}
public double celsius() {
return celsius;
}
public static void main(String[] args) {
System.out.println(Temperature.ofFahrenheit(212).celsius());
System.out.println(Temperature.ofCelsius(21.5).celsius());
}
}This prints 100.0 and then 21.5.
A factory method can call the private constructor because it lives inside the same class. A static method has no this, so it must create the object with new and return it. That is the static context rule applied to object creation.
Do not confuse this with the Factory Method design pattern from the Gang of Four book. That pattern relies on subclasses overriding a method. A static method cannot be overridden, as the chapter on hiding explains. This chapter covers the simpler idiom.
Why not just use constructors?
Static factories have four advantages over constructors.
They have names
A constructor must be named after the class. Two constructors with the same parameter types are also impossible. new Temperature(double) does not say whether the number is Celsius or Fahrenheit. Both ofCelsius(double) and ofFahrenheit(double) take a double, and the names remove the ambiguity. A constructor cannot do this, because it cannot be overloaded on meaning.
They do not have to create a new object
A constructor always allocates a new instance. A factory can return a cached or preallocated one. This helps with immutable value types that have few distinct values. The JDK does this with Boolean.valueOf(boolean) and Integer.valueOf(int), which caches values from -128 to 127.
public final class Digit {
private static final Digit[] CACHE = new Digit[10];
static {
for (int i = 0; i < CACHE.length; i++) {
CACHE[i] = new Digit(i);
}
}
private final int value;
private Digit(int value) {
this.value = value;
}
public static Digit of(int value) {
if (value < 0 || value > 9) {
throw new IllegalArgumentException("Not a digit: " + value);
}
return CACHE[value];
}
public int value() {
return value;
}
public static void main(String[] args) {
System.out.println(Digit.of(3) == Digit.of(3));
System.out.println(Digit.of(4).value());
try {
Digit.of(12);
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
}
}The output is true, 4, and Not a digit: 12. Ten objects exist for the whole program. The static block fills the array when the class is initialized. The array is declared above the block, so it already exists when the block runs.
The factory also validates its input. A constructor can validate too, but a factory can choose between returning an object and throwing, with a name that tells the reader what is being checked.
They can return a subtype
A constructor returns exactly its own class. A factory can return any subtype of its declared return type, and the caller never sees which one. Interfaces can hold static methods since Java 8, so an interface can offer its own factories.
public interface Greeter {
String greet(String name);
static Greeter formal() {
return name -> "Good day, " + name + ".";
}
static Greeter casual() {
return name -> "Hi " + name + "!";
}
}
class GreeterDemo {
public static void main(String[] args) {
System.out.println(Greeter.formal().greet("Ada"));
System.out.println(Greeter.casual().greet("Ada"));
}
}The caller depends only on Greeter. You can later change what formal() returns, or add a third implementation, without breaking any caller. java.util.List.of(...) works this way. The concrete class behind it is an implementation detail of the JDK.
They can hide construction detail
A factory can take a convenient input and do the conversion work, as ofFahrenheit does. It can also choose between several implementations based on the arguments. EnumSet.noneOf returns a different internal class depending on how many constants the enum has.
The flow below shows the three things a factory may do.
The disadvantages
Static factories have two costs.
- No subclassing when the constructors are private. A class with only private constructors cannot be extended by outside code. This is often wanted, because it pushes users toward composition. It is still a restriction. Package-private constructors allow subclasses inside the same package only.
- Harder to find. Constructors are listed together in the Javadoc and IDEs. A factory is an ordinary static method, so a reader has to know it exists. Naming conventions reduce this problem.
Common names
| Name | Typical use | Example |
|---|---|---|
| `of` | Aggregate several values into one instance | `List.of(1, 2, 3)` |
| `from` | Convert one value of another type | `Instant.from(temporal)` |
| `valueOf` | Older, more verbose form of `of` or `from` | `Integer.valueOf("42")` |
| `getInstance` | Return an instance, possibly shared | `Calendar.getInstance()` |
| `create` or `newInstance` | Guarantee a new instance each call | `Array.newInstance(type, n)` |
| `parse` | Build from text | `LocalDate.parse("2026-11-26")` |
Use new... or create... only when each call really returns a new object. A caller who sees getInstance should not rely on getting a distinct object.
A cache that is safe under threads
Caching in a static field creates shared mutable state, so thread safety applies. The following version keeps instances in a map. A plain HashMap would be unsafe here because two threads could modify it at once. ConcurrentHashMap.computeIfAbsent makes the check-then-insert step atomic.
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public final class CurrencyCode {
private static final Map<String, CurrencyCode> KNOWN = new ConcurrentHashMap<>();
private final String code;
private CurrencyCode(String code) {
this.code = code;
}
public static CurrencyCode of(String code) {
if (code == null || code.length() != 3) {
throw new IllegalArgumentException("Expected a 3-letter code: " + code);
}
String normalized = code.toUpperCase(Locale.ROOT);
return KNOWN.computeIfAbsent(normalized, CurrencyCode::new);
}
public String code() {
return code;
}
public static void main(String[] args) {
CurrencyCode a = CurrencyCode.of("eur");
CurrencyCode b = CurrencyCode.of("EUR");
System.out.println(a == b);
System.out.println(a.code());
}
}This prints true and EUR. The factory normalizes the input, so "eur" and "EUR" map to the same object.
Common errors
- Leaving a public constructor in place. If the constructor is still public, callers can bypass the factory. They then skip validation and caching, and
==comparisons stop working. Make the constructor private (or package-private) and test that it is. - Using
==on factory results without a guarantee. Only compare with==when the class documents that it returns a canonical instance, asDigitdoes. Otherwise useequals. - Expecting a static factory to be overridden. Defining
ofCelsiusin a subclass hides the parent method. It does not replace it. Which one runs depends on the name used at the call site, not on the runtime object. - Hiding expensive or side-effecting work behind an innocent name. A method named
ofshould be cheap and predictable. Use a name likeloadoropenwhen it reads files or connects to something. - Returning
nullfor bad input. Throw an exception such asIllegalArgumentException, or returnOptionalwhen absence is a normal outcome. A null return pushes the failure to some later line. - Making every class a static-factory class by habit. A plain class with two simple constructors is fine. Add factories when you need names, caching, subtypes, or validation that a constructor cannot express cleanly.
Choosing between a constructor and a factory
Use a constructor when the class is simple, has one obvious way to be built, and you want subclassing to work. Use a static factory when one or more of these hold:
- Several creation routes take the same parameter types.
- You want to reuse instances of an immutable value.
- Callers should depend on an interface and not on the concrete class.
- You need to reject or normalize input before an object exists.
Many classes provide both: a private constructor for the factories to use, and factories as the public API. For classes with many optional parameters, a builder is usually better than a pile of factory overloads, but that is a separate pattern.
Exercise
In the Digit class, why does Digit.of(3) == Digit.of(3) print true, and what would break that guarantee if you changed the class?
Show answer
The factory returns the same preallocated object from the static CACHE array every time it is asked for 3, so both calls produce one reference. The guarantee breaks if the constructor becomes public, or if of calls new Digit(value) instead of reading from the cache. Either change allows more than one object for the same digit, and == then compares references that differ.
Exercise
A teammate writes public static Temperature ofKelvin(double k) in a subclass PreciseTemperature extends Temperature, intending to override a parent method of the same signature. Does this override it, and what is it called?
Show answer
No. A static method cannot be overridden. A subclass method with the same signature hides the parent's method. The call is resolved from the type named at the call site, not from the runtime object. Note also that Temperature in this chapter is final with a private constructor, so it could not be subclassed in the first place.
Exercise
Why does CurrencyCode.of use ConcurrentHashMap.computeIfAbsent rather than a HashMap with get followed by put?
Show answer
The KNOWN map is static state shared by every thread. With a HashMap, two threads could both see a missing key and each insert a different object, and concurrent writes can also corrupt the map. computeIfAbsent on a ConcurrentHashMap performs the check and the insert as one atomic step, so every caller gets the same instance.