📜  Java构造函数和静态工厂方法的区别

📅  最后修改于: 2021-09-15 01:53:37             🧑  作者: Mango

每当我们创建一个对象时,都会执行一些代码来执行该对象的初始化。这段代码只不过是一个构造函数,因此构造函数的主要目的是执行对象的初始化而不是创建对象。让我们来看看编写构造函数的基本规则集。它们如下:

  1. 类的名称和构造函数的名称必须相同。
  2. 返回类型的概念也不适用于构造函数甚至 void 。错误地,如果我们试图为构造函数声明返回类型,那么我们不会得到编译时错误,因为编译器将其视为方法。
  3. 构造函数唯一适用的修饰符是 public、private、protected 和 default。如果我们尝试使用任何其他修饰符,我们将收到一个编译时错误,提示修饰符 name_of_modifier 不允许在这里。

默认构造函数

编译器负责生成默认构造函数,但不负责生成 JVM。如果我们没有编写任何构造函数,那么只有编译器会生成默认构造函数,即如果我们至少编写一个构造函数,那么Java的每个类都可以包含一个构造函数,它可能是由编译器生成的默认构造函数,也可能是由编译器明确提供的自定义构造函数程序员,但不能同时进行。

默认构造函数的原型如下:

  • 它始终是一个无参数的构造函数
  • 默认构造函数的访问修饰符与类的访问修饰符完全相同。
  • 它只包含一行 super() 它是对超类构造函数的无参数调用。

静态工厂方法

如果我们正在调用一个方法并且该方法返回相同的类对象,则通过使用类名,则这种类型的方法称为静态工厂方法。静态工厂方法是返回本机类实例的方法。与构造函数不同,静态工厂方法具有阐明代码的名称。在静态工厂方法中,我们不需要在每次调用时创建一个新对象,即如果需要,可以缓存和重用对象。我们也可以返回它们返回类型的子类型。

例子:

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");
    }
}


输出:

因此,从上面的文章中,我们可以清楚地总结出它们之间的区别如下:

                        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()