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,"有参构造器");
2. The more commonly used method: create objects through reflection newInstance(). This method uses constructors.
Demo demo2=(Demo) Class.forName("Demo").newInstance();
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();
(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!