January 9, 2009 Leave a comment
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.
public static void main(String  args)
ConstructorDemo ConObj = new ConstructorDemo();
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 = 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.
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.
1. Classes without public or protected methods cannot be subclassed.
2. They are not readily distinguishable from other static method.