Sunday, June 23, 2024
Home Design Patterns Using Static Factory Methods – Learning Effective Java Item 1

Using Static Factory Methods – Learning Effective Java Item 1

Using Static Factory Methods – Learning Effective Java Item 1

In this series, we will learn how to apply concepts of highly popular Java book, Effective Java, 2nd Edition. In the first article, we will discuss about Effective Java’s Item 1, i.e, Using Static Factory Methods.  We will see how we can apply in our coding using example.

Let us go through the following example for better understanding.

class ExampleFragment : Fragment() {
companion object {
fun newInstance() : ExampleFragment {
return ExampleFragment()

In the above example, we are creating a new Object every time when we call newInstance() method. This is a static method (In Kotlin, methods inside companion object are static).

Related Links
  • Unlike constructors, these methods have meaningful names which results in easier to read code. Also if we want to create objects using different parameters, we have to create multiple constructors taking different parameters. Users doesn’t know the difference between the two unless they have proper documentation which can be avoided as we will provide meaningful name.
  • Unlike constructors, they don’t need to create a new object each time they’re invoked.
  • Unlike constructors, they can return an object of any subtype of their return type.
  • Primary disadvantages of using static factory methods is if there are no public or protected constructors in that class, then that particular class cannot be subclassed.
  • Static factory methods are not distinguishable from other static methods so that developer doesn’t know sometimes that these factory methods exists until unless they are specified.

In the next article of this, we will discuss on the Item 2 from Effective Java. If you are interested in this book, checkout the following link to buy.


Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.