Object construction: static factory method instead of constructor [Effective Java]

14 09 2013

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

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

Donate Button with Credit Cards

Thank You!




Give Your feedback:

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: