Providing static factory methods instead of constructors

Whenever we want an object to initialize itself, we normally go for public constructor definition. But have you ever think about static factory method? A class can provide similar or some addition fetchers as in constructor to its clients with static factory method.
Constructor allows object to initialize themselves when they are created. Once defined, the constructor is automatically called immediately as the object is created, before the new operator completes.

A simple example of constructor:
ConstructorExample.java

class ConstructorDemo
{
    public int a=42;
    ConstructorDemo()
    {
        System.out.println(“a = ” + a);
    }
}

class ConstructorExample
{
    public static void main(String [] args)
    {
        ConstructorDemo ConObj = new ConstructorDemo();
    }
}
Output:
a = 42

There is a less popular technique that should also be a part of every programmer’s toolkit for the similar propose of constructor. A class can provide a public static factory method, which is simply a static method that returns an instance of the class. When a method is static, it can be accessed before any objects of its class are created, and without reference to any object.

A simple example of constructor:
StaticExample.java

class StaticDemo
{
    static int a=42;
    static void callme()
    {
        System.out.println(“a = ” + a);
    }
}
class StaticExample
{
    public static void main(String [] args)
    {
        StaticDemo.callme();
    }
}

Output:
a = 42

Apart from all, defining static factory method has both advantage as well as disadvantage, so according to the requirement we should have to use this method.

The advantages of static factory method are:
1. Unlike constructor, it has names which make class easier to use.
2. Unlike constructor, they are not required to create a new object each time they are invoked.
3. Unlike constructor, they can return an object of any subtype of their return type.
The disadvantages of static factory methods are:
1. Classes without public or protected methods cannot be subclassed.
2. They are not readily distinguishable from other static method.
Reference from: Effective Java, Joshua Bloch
Advertisements

One Response to Providing static factory methods instead of constructors

  1. jim says:

    ok, all well and good.

    explain yourself … tell the readers what “StaticDemo.callme();” did in the last example and
    what they gain by doing things that way…

    don’t leave them hanging…

Leave a Reply

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

%d bloggers like this: