Home>Article>Java> What are the several ways to create objects in java

What are the several ways to create objects in java

王林
王林 Original
2020-05-26 14:23:30 5929browse

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

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

(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 constructor = Employee.class.getConstructor(); Employee emp3 = constructor.newInstance();

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

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

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!

Statement:
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