What is it
Static factory method is a public static method that is used to create object – exactly the same as constructor. So when it is better than usual constructor?
– unlike constructors, they have names, so you can easily distinguish and know what kind of object they actually build
– unlike constructors, they do not have to create new instance each time they are called, so in other words you can easily make this class a singleton
– they can return an object of any subtype of their return type
– they reduce verbosity of creating parameterized type instances. So instead of header:
public Bread(boolean old);
you can use
public static Bread createOldBread();
public static Bread createFreshBread();
– A class without public or protected constructors can’t be subclassed
– static factory methods are not easily distinguishable from any other static methods, so good naming is required
Effective Java (Joshua Bloch) is a book with advanced Java programming techniques that make Java code more robust and readable. I am currently reading it and this is why these [Effective Java] posts come up here. These are summaries of chapters that are most valuable in my opinion.
Did I help you?
I manage this blog and share my knowledge for free sacrificing my time. If you appreciate it and find this information helpful, please consider making a donation in order to keep this page alive and improve quality