I am going through Effective Java and some of my things which I consider as standard are not suggested by the book, for instance creation of object, I was under the impression that constructors are the best way of doing it and books says we should make use of static factory methods, I am not able to few some advantages and so disadvantages and so am asking this question, here are the benefits of using it.
Advantages:
- One advantage of static factory methods is that, unlike constructors, they
have names.- A second advantage of static factory methods is that, unlike constructors,
they are not required to create a new object each time they’re invoked.- A third advantage of static factory methods is that, unlike constructors,
they can return an object of any subtype of their return type.- A fourth advantage of static factory methods is that they reduce the verbosity
of creating parameterized type instances.Disadvantages:
- The main disadvantage of providing only static factory methods is that
classes without public or protected constructors cannot be subclassed.- A second disadvantage of static factory methods is that they are not
readily distinguishable from other static methods.Reference: Effective Java, Joshua Bloch, Edition 2, pg: 5-10
I am not able to understand the fourth advantage and the second disadvantage and would appreciate if someone can explain those points. I would also like to understand how to decide to use whether to go for Constructor or Static Factory Method for Object Creation.
Advantage 4: When using a constructor, you have
vs
this advantage will be gone in Java 7, when the diamond syntax will be introduced
Disadvantage 2. You can’t easily tell whether a given
staticmethod is used for constructor, or for something else.As for how to choose – there is no single recipe for that. You can weigh all of the above advantages and disadvantages given a use-case, but most often it will just be a decision driven by experience.