Home > Java > Javagetting Started > What are the ways to create objects in Java

What are the ways to create objects in Java

王林
Release: 2020-07-15 16:51:23
forward
2504 people have browsed it

What are the ways to create objects in Java

Several ways to create objects:

(Recommended tutorial: java introductory tutorial)

1. This is the most Commonly used methods: create objects through new. This method requires the use of a constructor.

Demo demo1=new Demo();
Demo demo2=new Demo(1,"有参构造器");
Copy after login

2. The more commonly used method: create objects through reflection newInstance(). This method uses constructors.

Demo demo2=(Demo) Class.forName("Demo").newInstance();
Copy after login

3. Through the clone method of the Object class. You need to implement the Cloneable interface and override the clone method of the object class.

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.

Demo demo4=(Demo) demo2.clone();
Copy after login

(Video tutorial recommendation: java video tutorial)

4. Deserialization

JSON data and Java objects are often processed in java conversion, namely serialization and 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, although this interface does not have any methods. No constructors will be called.

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

Related labels:
source:cnblogs.com
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