what’s on java object creation-static factory method

Many of you aware of static factory method which is a simple static method returns an instance of the class. An example like public static Boolean valueOf(boolean yourVal). No let me explain some of the advantages of using static factory method.

Some of the advantages:

1. When ever we invoke a constructor like Emp emp = new Emp() it creates an object. But using static factory method like Emp emp = Emp.getInstance() (Consider getInstance() is a static method which return type is EMP object) will always returns single Emp object no matter how many times we called them.

2. We could create any number of static methods with different names like getCar() return car object, getBreak() returns break object, But constructors have the constraints like should have the class name as their name. So we might need to differentiate using the parameter (using method overloading) which is good but on the readability point of view it will confuse.

So all good what about disadvantages. yah it has a main disadvantages,

Since we have all static methods naturally the constructor will be private. So we can’t really extends the class. Some of the object orientations might me lost.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com 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