How to create objects in java
How to create an object in java: 1. Use the new keyword; 2. Use the newInstance method of the Class class, which can call the constructor without parameters to create an object; 3. Use the newInstance method of the Constructor class; 4. Use clone method; 5. Use deserialization.
The operating environment of this tutorial: windows7 system, java8 version, DELL G3 computer.
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 | } → Called the constructor |
Use the newInstance method of the Class class | } → Called the constructor |
Using the newInstance method of the Constructor class | } → The constructor was called |
Using the clone method | } →The constructor was not called |
Use deserialization | } → The constructor is not called |
If you run the program at the end, you You will find that methods 1, 2, and 3 use constructors to create objects, and methods 4 and 5 do not call constructors.
1. Use the new keyword
This is the most common and simplest way to create objects. 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
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;
3. Use the newInstance method of the Constructor class
and the newInstance method of the Class class Much like the java.lang.reflect.Constructor class, there is also a newInstance method to 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;
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. To understand the difference between the two newInstance methods, please read this article Creating objects through Reflection in Java with Example.
4. Use the clone method
Whenever we When the clone method of an object is called, the jvm will create a new object and 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;
5. Use deserialization
When we serialize and deserialize an object, 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;
We can see from the above bytecode fragment that except for the first method, the other four methods are all converted For invokevirtual (a direct method of creating an object), the first method is transformed into two calls, new and invokespecial (a constructor call).
Example
Let us take a look at creating objects 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; } }
In the following Java program, we will use 5 method to create an Employee object. You can find the code from GitHub.
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'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'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()); } }
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
Related video tutorial recommendations: Java video tutorial
The above is the detailed content of How to create objects in java. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.
