List all possible/different ways to create a Java object

The ways I know and have tried so far:

1. Using new keyword
This is the most common way to create an object in java. Most of the time, Java objects are created in this way.

MyTestObject obj = new MyTestObject();

2. Using Class.forName()
If we know the name of the class & if it has a public default constructor we can create an object in this way.

MyTestObject obj = (MyTestObject) Class.forName(“sing.test.MyTestClass”).newInstance();

3. Using clone()
The clone() can be used to create a copy of an existing object.

MyTestObject anotherObj = new MyTestObject();
MyTestObject obj = anotherObject.clone();

4. Using object deserialization
Object deserialization is nothing but creating an object from its serialized form.

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


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: