Creation of Objects: Constructors or Static Factory Methods
Posted
by
Rachel
on Stack Overflow
See other posts from Stack Overflow
or by Rachel
Published on 2011-01-06T16:44:19Z
Indexed on
2011/01/06
16:53 UTC
Read the original article
Hit count: 246
java
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.
I am not able to understand this advantage and would appreciate if someone can explain this point
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.
I am not getting this point and so would really appreciate some explanation.
Reference: Effective Java, Joshua Bloch, Edition 2, pg: 5-10
Also, How to decide to use whether to go for Constructor or Static Factory Method for Object Creation ?
© Stack Overflow or respective owner