The Wayback Machine - https://web.archive.org/web/20240530065550/https://www.geeksforgeeks.org/difference-between-constructor-and-static-factory-method-in-java/
Open In App

Difference Between Constructor and Static Factory Method in Java

Last Updated : 09 Jun, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

Whenever we are creating an object some piece of code will be executed to perform initialization of that object. This piece of code is nothing but a constructor, hence the main purpose of the constructor is to perform initialization of an object but not to create an object. Let us go through the basic set of rules for writing a constructor. They are as follows:

  1. The name of the class and the name of the constructor must be the same.
  2. Return type concept is not applicable for constructor even void also. By mistake, if we are trying to declare return type for the constructor then we won’t get a compile-time error because the compiler treats it as a method.
  3. The only applicable modifiers for the constructor are public, private, protected, and default. If we are trying to use any other modifier we will get a compile-time error saying modifier name_of_modifier Not allowed here.

Default Constructor 

A compiler is responsible to generate the default constructor but not JVM. If we are not writing any constructor then only the compiler will generate the default constructor i.e if we are writing at least one constructor hence every class in java can contain a constructor it may be a default constructor generated by a compiler or customize constructor explicitly provided by the programmer but not both simultaneously.

The prototype of the default constructor is as follows:

  • It is always a no-arg constructor
  • The access modifier of the default constructor is exactly the same as the access modifier of the class.
  • It contains only one line super() it is a no-argument call to the superclass constructor.

Static Factory Methods

By using a class name if we are calling a method and if that method returns the same class object then such type of method is called static factory method. The static factory methods are methods that return an instance of the native class. The static factory method has names that clarify the code, unlike the constructors. In the static factory method, we do not need to create a new object upon each invocation i.e object can be cached and reused if required. We can also return the subtype of their return type. 

The first line inside every constructor should be either super() or this() and if we are not writing anything then the compiler will always place super()

Example: 

Java




// Java Program to showcase Difference Between
// Constructor and Static Factory method
 
// Importing all utility classes from
// java.util package
// Importing all input output classes
import java.io.*;
import java.util.*;
 
// Main class
// To find out complex number
public final class GFG {
 
    // Method 1
    // Static factory method returns an object of this
    // class.
    public static GFG valueOf(float real, float imaginary)
    {
        return new GFG(real, imaginary);
    }
 
    // Caller cannot see this private constructor.The only
    // way to build a GFG is by calling the static factory
    // method.
 
    // Constructor
    private GFG(float real, float imaginary)
    {
 
        // This keyword refers to current object itself
        this.real = real;
        this.imaginary = imaginary;
    }
 
    private float real;
    private float imaginary;
 
    // Method 2
    // Main driver method
    public static void main(String[] args)
    {
        // Creating an object of GFG and
        // calling an static factory method valueOf()
        GFG n = GFG.valueOf(2, 4);
 
        // Print and display the complex number
        System.out.println(n.real + "+" + n.imaginary
                           + "i");
    }
}


Output:

Hence, from the above article, we can conclude the differences between them clearly which are as follows:

                        Constructor                               Static factory method
The constructor doesn’t have a meaningful name, so they always restricted to the standard naming convention   The static factory method can have a meaningful name hence we can explicitly convey what this method does. 
Constructors can’t have any return type not even void. Static factory methods can return the same type that implements the method, a subtype, and also primitives. 
Inside the constructor, we can only perform the initialization of objects.  Inside static factory method other than initialization if we want to perform any activity for every object creation like increasing count value for every object creation we can do this in the static factory method.  
Constructor always creates a new object inside the heap, so it is not possible to return a cached instance of the class from a constructor.  But Factory methods can take advantage of caching i.e we can return the same instance of Immutable class from the factory method instead of always creating a new object. 
The first line inside every constructor should be either super() or this() But inside the factory method, it is not necessary that the first line must be either super() or this()


Similar Reads

How to Check the Accessibility of the Static and Non-Static Variables by a Static Method?
The static keyword is a non - access modifier in Java which can be used for variables, methods, and block of code. Static variables in Java belong to the class i.e it is initialized only once at the start of the execution. By using static variables a single copy is shared among all the instances of the class, and they can be accessed directly by cl
3 min read
Difference between static and non-static method in Java
A static method is a method that belongs to a class, but it does not belong to an instance of that class and this method can be called without the instance or object of that class. Every method in java defaults to a non-static method without static keyword preceding it. Non-static methods can access any static method and static variable, without cr
6 min read
Spring - Static Factory Method
Static factory methods are those that can return the same object type that implements them. Static factory methods are more flexible with the return types as they can also return subtypes and primitives too. Static factory methods are used to encapsulate the object creation process. In the Spring framework if we want to create a bean using the stat
4 min read
Difference between static and non-static variables in Java
There are three types of variables in Java: Local VariablesInstance VariablesStatic Variables The Local variables and Instance variables are together called Non-Static variables. Hence it can also be said that the Java variables can be divided into 2 categories: Static Variables: When a variable is declared as static, then a single copy of the vari
4 min read
Difference Between Static and Non Static Nested Class in Java
Nested classes are divided into two categories namely static and non-static. Nested classes that are declared static are called static nested classes. Non-static nested classes are called inner classes. A class can either be static or non-static in java. So there is a lot of difference between making a class static or non-static. There are two kind
4 min read
Difference between Static-1 and Static-0 hazard
Static hazard occur in combinational circuits and can be eliminated by using redundant gates. Static hazard is classified as: 1. Static-1 hazard : If the output is currently at logic state 1 and after the input changes its state, at the same moment the output changes to 0 before settling on 1, then it is a Static-1 hazard. 2. Static-0 hazard : If t
1 min read
Java Program to Show Inherited Constructor Calls Parent Constructor By Default
In java, there exists a very important keyword known as super() keyword in java which is widely used in java being object-oriented and hence inheritance comes into play. So whenever we use super keyword inside a child constructor then it calls the default parent constructor by itself. Example 1 Java Code // Java Program to Demonstrate Inherited con
2 min read
Why non-static variable cannot be referenced from a static method in Java
Java is one of the most popular and widely used programming language and platform. Java is Object Oriented. However, it is not considered as a pure object-oriented as it provides support for primitive data types (like int, char, etc). In java, methods can be declared as either static or non-static. In this article, let's discuss why non-static vari
4 min read
Java Program to Check the Accessibility of an Static Variable By a Static Method
The Static Keyword is a non-access modifier in Java mainly used for memory management. This static keyword is mainly applicable for the following: VariablesMethodsBlocksNested Class Static Variable is a variable that is declared as static means a single copy of the variable is created and shared among all objects at the class level. Static method i
3 min read
Difference Between Singleton and Factory Design Pattern in Java
Design patterns are essential tools for creating maintainable and scalable software. Two commonly used design patterns in Java are the Singleton and Factory patterns. This article provides an introduction to the Singleton and Factory design patterns with examples. Singleton Design Pattern in JavaThe Singleton pattern is a creational design pattern
3 min read
Practice Tags :