Java Zero to All All questionsPractise free
Interview questions › Java Foundations — Zero to Basics › OOP I — Classes, Objects, Constructors

What problem do static factory methods solve that constructors cannot, and what's the trade-off?

Level III · MidOOP I — Classes, Objects, Constructors
Short answer

Static factories can have descriptive names (Optional.of vs Optional.empty), can return a cached or subtype instance instead of always allocating, and can hide the implementation type behind an interface — none of which a constructor can do.

Explanation

Examples are Integer.valueOf, List.of, and Optional.of. The trade-off is that a class with only private constructors and static factories cannot be subclassed, and the factory methods are harder to discover than 'new' in IDE autocomplete.

Common mistakes
  • Saying static factories are only for singletons.
  • Ignoring that classes with only private constructors cannot be subclassed.

Can you say this out loud in two minutes? Drill it in a timed mock interview, with flashcards and runnable code for OOP I — Classes, Objects, Constructors.

Practise free

More on OOP I — Classes, Objects, Constructors