Home > Java > javaTutorial > body text

What are the several ways to create objects in java

王林
Release: 2020-05-26 14:23:30
Original
6031 people have browsed it

What are the several ways to create objects in java

There are five ways to create objects in Java, which are:

1. Use the new keyword

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

Employee emp1 = new Employee();
Copy after login

2. Use the newInstance method of the Class class

This newInstance method calls the parameterless constructor to create an object.

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

Employee emp2 = Employee.class.newInstance();
Copy after login

(Video tutorial recommendation: java video)

3. Use the Constructor class The newInstance method

is very similar to 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();
Copy after login

4. Use the clone method

Whenever we call the clone method of an object, 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();
Copy after login

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();
Copy after login

Recommended tutorial: Getting started with java development

The above is the detailed content of What are the several ways to create objects in java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template