I want to know how to create objects in Java

Asked 2 years ago, Updated 2 years ago, 24 views

I recently talked with my colleagues about how to create objects. Most people use constructors to create objects, but all of a sudden, I wondered if there was any other way. What are some ways to create objects?

java

2022-09-22 22:09

1 Answers

First of all, there is a method using the new keyword. This is the most common way, and almost all objects are created like this. MyObject object = new MyObject();

The second method is to write Class.forName() If we know the name of the class and the class has a public default constructor defined, we can create it this way.

MyObject object = (MyObject) Class.forName("subin.rnd.MyObject").newInstance();

Third, it is a method using clone(). If an object already exists, it is created by copying it.

MyObject anotherObject = new MyObject();
MyObject object = (MyObject) anotherObject.clone();

The fourth is the object designation method.

ObjectInputStream inStream = new ObjectInputStream(anInputStream );
MyObject object = (MyObject) inStream.readObject();

This is how serialization is used to create objects.


2022-09-22 22:09

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.