Home Java javaTutorial Summary of 5 ways to create objects in Java

Summary of 5 ways to create objects in Java

Feb 11, 2017 pm 04:07 PM

This article mainly introduces a summary of the 5 ways to create objects in Java. The editor thinks it is quite good. Now I will share it with you and give it a reference. Let’s follow the editor and take a look

As Java developers, we create many objects every day, but we usually use dependency management systems, such as Spring, to create objects. However there are many ways to create objects, which we will learn in this article.

There are 5 ways to create objects in Java. Their examples and their bytecodes are given below


Use the new keyword } → Call the constructor
Use the newInstance method of the Class class } → Call the constructor
Use the newInstance method of the Constructor class } → Call the constructor
Use the clone method } → No constructor called
Use deserialization } → No constructor called

as Java developers, we create many objects every day, but we usually use dependency management systems, such as Spring, to create objects. However there are many ways to create objects, which we will learn in this article.

There are 5 ways to create objects in Java. Their examples and their bytecodes are given below

If you run the program at the end, you will find method 1, 2 and 3 use the constructor to create objects, and methods 4 and 5 do not call the constructor.

1. Use the new keyword

This is the most common and simplest way to create an object. In this way, we can call any constructor (parameterless and parameterized).

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
Copy after login

2. Use the newInstance method of the 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 the object.

We can create objects by calling the newInstance method in the following way:

Employee emp2 = (Employee) Class.forName("org.programming.mitra.exercises.Employee").newInstance();
// 或者

Employee emp2 = Employee.class.newInstance();
51: invokevirtual  #70  // Method java/lang/Class.newInstance:()Ljava/lang/Object;
Copy after login

3. Use the newInstance method of the Constructor class

Much like the newInstance method of the Class class, there is also a newInstance method in the java.lang.reflect.Constructor class that can create objects. We can call parameterized and private constructors through this newInstance method.

Constructor<Employee> constructor = Employee.class.getConstructor();
Employee emp3 = constructor.newInstance();
111: invokevirtual #80 // Method java/lang/reflect/Constructor.newInstance:([Ljava/lang/Object;)Ljava/lang/Object;
Copy after login

These two newInstance methods are what everyone calls reflection. In fact, the newInstance method of Class internally calls the newInstance method of Constructor. This is also the reason why many frameworks, such as Spring, Hibernate, Struts, etc., use the latter. Want to understand the difference between these two newInstance methods,

4. Use the clone method

Whenever we call the clone method of an object, the jvm will create a new object, copy all the contents of the previous object into it. Creating an object using the clone method does not call any constructor.

To use the clone method, we need to first implement the Cloneable interface and implement the clone method defined by it.

Employee emp4 = (Employee) emp3.clone();
162: invokevirtual #87 // Method org/programming/mitra/exercises/Employee.clone ()Ljava/lang/Object;
Copy after login

5. Using deserialization

When we serialize and deserialize an object, the jvm will Create a separate object for us. During deserialization, the jvm creates the object and does not call any constructor.

In order to deserialize an object, we need to make our class implement the Serializable interface

ObjectInputStream in = new ObjectInputStream(new FileInputStream("data.obj"));
Employee emp5 = (Employee) in.readObject();
261: invokevirtual #118  // Method java/io/ObjectInputStream.readObject:()Ljava/lang/Object;
Copy after login

We get the bytes from above As you can see from the code snippet, except for the first method, the other four methods are all converted into invokevirtual (direct method of creating an object), and the first method is converted into two calls, new and invokespecial (constructor call).

Example

Let us take a look at creating an object for the following Employee class:

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

In the following Java program, we will create Employee objects in 5 ways.

public class ObjectCreation {
  public static void main(String... args) throws Exception {
    // By using new keyword
    Employee emp1 = new Employee();
    emp1.setName("Naresh");
    System.out.println(emp1 + ", hashcode : " + emp1.hashCode());
    // By using Class class&#39;s newInstance() method
    Employee emp2 = (Employee) Class.forName("org.programming.mitra.exercises.Employee")
                .newInstance();
    // Or we can simply do this
    // Employee emp2 = Employee.class.newInstance();
    emp2.setName("Rishi");
    System.out.println(emp2 + ", hashcode : " + emp2.hashCode());
    // By using Constructor class&#39;s newInstance() method
    Constructor<Employee> constructor = Employee.class.getConstructor();
    Employee emp3 = constructor.newInstance();
    emp3.setName("Yogesh");
    System.out.println(emp3 + ", hashcode : " + emp3.hashCode());
    // By using clone() method
    Employee emp4 = (Employee) emp3.clone();
    emp4.setName("Atul");
    System.out.println(emp4 + ", hashcode : " + emp4.hashCode());
    // By using Deserialization
    // Serialization
    ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("data.obj"));
    out.writeObject(emp4);
    out.close();
    //Deserialization
    ObjectInputStream in = new ObjectInputStream(new FileInputStream("data.obj"));
    Employee emp5 = (Employee) in.readObject();
    in.close();
    emp5.setName("Akash");
    System.out.println(emp5 + ", hashcode : " + emp5.hashCode());
  }
}
Copy after login

The program will output:

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
Copy after login

The above is the entire content of this article, I hope It will be helpful to everyone's learning, and I hope everyone will support the PHP Chinese website.

For more related articles summarizing the 5 ways to create objects in Java, please pay attention to the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to simplify field mapping issues in system docking using MapStruct? How to simplify field mapping issues in system docking using MapStruct? Apr 19, 2025 pm 06:21 PM

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

How to elegantly obtain entity class variable names to build database query conditions? How to elegantly obtain entity class variable names to build database query conditions? Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

What is the difference between memory leaks in Java programs on ARM and x86 architecture CPUs? What is the difference between memory leaks in Java programs on ARM and x86 architecture CPUs? Apr 19, 2025 pm 11:18 PM

Analysis of memory leak phenomenon of Java programs on different architecture CPUs. This article will discuss a case where a Java program exhibits different memory behaviors on ARM and x86 architecture CPUs...

How to correctly divide business logic and non-business logic in hierarchical architecture in back-end development? How to correctly divide business logic and non-business logic in hierarchical architecture in back-end development? Apr 19, 2025 pm 07:15 PM

Discussing the hierarchical architecture problem in back-end development. In back-end development, common hierarchical architectures include controller, service and dao...

How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to convert names to numbers to implement sorting within groups? How to convert names to numbers to implement sorting within groups? Apr 19, 2025 pm 01:57 PM

How to convert names to numbers to implement sorting within groups? When sorting users in groups, it is often necessary to convert the user's name into numbers so that it can be different...

What is the reason why the browser does not respond after the WebSocket server returns 401? How to solve it? What is the reason why the browser does not respond after the WebSocket server returns 401? How to solve it? Apr 19, 2025 pm 02:21 PM

The browser's unresponsive method after the WebSocket server returns 401. When using Netty to develop a WebSocket server, you often encounter the need to verify the token. �...

Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

See all articles