SoFunction
Updated on 2025-03-08

Five different methods in Java to create objects

Preface

As Java developers, we create a large number of objects every day, but we always use management dependency systems (such as Spring frameworks) to create these objects. In fact, there are other ways to create objects, which I will introduce in detail in the following article.

1. Use the new keyword

This is the most common way to create objects, and it is also very simple. By using this method we can call any constructor we need to call.

Employee emp1 = new Employee();
0: new      #19     // class org/programming/mitra/exercises/Employee
 3: dup
 4: invokespecial #21     // Method org/programming/mitra/exercises/Employee."":()V

2. Use the newInstance method of class class

We can also use the newInstance method of the class class to create objects. This newInstance method calls the parameterless constructor to create an object.

We can create objects using newInstance() in the following way:

Employee emp2 = (Employee) ("").newInstance();

or

Employee emp2 = ();
51: invokevirtual  #70  // Method java/lang/:()Ljava/lang/Object;

3. Use the newInstance method of the constructor class

With the use of class classnewInstanceSimilar methods,There is a class that can be used to create objectsnewInstance()Function method. By using thisnewInstanceMethods we can also call parameterized constructors and private constructors.

Constructor<Employee> constructor = ();
Employee emp3 = ();
111: invokevirtual #80 // Method java/lang/reflect/:([Ljava/lang/Object;)Ljava/lang/Object;

ThesenewInstance() Methods are considered to be reflection means to create objects. In fact, the internal classnewInstance()Methods use constructor classnewInstance() method. This is why the latter is preferred and uses different frameworks likeSpring, Hibernate, Strutswait.

4. Use the clone method

Actually, whenever we callcloneMethods, the JAVA virtual machine creates a new object for us and copies the contents of the previous object into this new object. usecloneMethod creation objects will not call any constructors.

For use in objectsclone()Methods, where we need to implement cloneable types and define clone methods.

Employee emp4 = (Employee) ();
162: invokevirtual #87 // Method org/programming/mitra/exercises/ ()Ljava/lang/Object;

5. Use deserialization

Whenever we serialize and deserialize an object, the JAVA virtual machine creates a separate object for us. In deserialization, the JAVA virtual machine does not use any constructor to create objects.

Serializing an object requires us to implement a serializable interface in the class.

ObjectInputStream in = new ObjectInputStream(new FileInputStream(""));
Employee emp5 = (Employee) ();
261: invokevirtual #118  // Method java/io/:()Ljava/lang/Object;

As we can see in the above byte code snippet, except for the first one being converted into a new function and ainvokespecialExcept for the instruction, all other 4 methods are called and converted toinvokevirtual

Example

Let's take a look at what is ready to create an object Employee kind:

class Employee implements Cloneable, Serializable {
  private static final long serialVersionUID = 1L;
  private String name;
  public Employee() {
    ("Employee Constructor Called...");
  }
  public String getName() {
    return name;
  }
  public void setName(String name) {
     = name;
  }
  @Override
  public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + ((name == null) ? 0 : ());
    return result;
  }
  @Override
  public boolean equals(Object obj) {
    if (this == obj)
      return true;
    if (obj == null)
      return false;
    if (getClass() != ())
      return false;
    Employee other = (Employee) obj;
    if (name == null) {
      if ( != null)
        return false;
    } else if (!())
      return false;
    return true;
  }
  @Override
  public String toString() {
    return "Employee [name=" + name + "]";
  }
  @Override
  public Object clone() {
    Object obj = null;
    try {
      obj = ();
    } catch (CloneNotSupportedException e) {
      ();
    }
    return obj;
  }
}

In the following Java program we use 5 ways to createEmployeeObject.

public class ObjectCreation {
  public static void main(String... args) throws Exception {
    // By using new keyword
    Employee emp1 = new Employee();
    ("Naresh");
    (emp1 + ", hashcode : " + ());
    // By using Class class's newInstance() method
    Employee emp2 = (Employee) ("")
                .newInstance();
    // Or we can simply do this
    // Employee emp2 = ();
    ("Rishi");
    (emp2 + ", hashcode : " + ());
    // By using Constructor class's newInstance() method
    Constructor<Employee> constructor = ();
    Employee emp3 = ();
    ("Yogesh");
    (emp3 + ", hashcode : " + ());
    // By using clone() method
    Employee emp4 = (Employee) ();
    ("Atul");
    (emp4 + ", hashcode : " + ());
    // By using Deserialization
    // Serialization
    ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(""));
    (emp4);
    ();
    //Deserialization
    ObjectInputStream in = new ObjectInputStream(new FileInputStream(""));
    Employee emp5 = (Employee) ();
    ();
    ("Akash");
    (emp5 + ", hashcode : " + ());
  }
}

The output results of this program are as follows:

Employee Constructor Called...
Employee [name=Naresh], hashcode : -1968815046
Employee Constructor Called...
Employee [name=Rishi], hashcode : 78970652
Employee Constructor Called...
Employee [name=Yogesh], hashcode : -1641292792
Employee [name=Atul], hashcode : 2051657
Employee [name=Akash], hashcode : 63313419

The above content is about 5 different methods for creating objects in Java. I hope it will be helpful for you to learn Java. Thank you for your support.