Thursday, February 3, 2011

Different ways to create an object in Java

This is my first post on my blog. So I thought this is the most relevant question when we start with Java. Also, this question is asked many times in interviews so again it is very important.

What are the different ways to create an object/
As far as I know, there are four ways to create object in java and the story is

1. Using new keyword
This is the most common way to create an object in java. I read somewhere that almost 99% of objects are created in this way.

MyObject object = new MyObject();

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.

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

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

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

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

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

Creating objects and their maintenance is a very critical decision. That's why we have a list of design patterns which a lot of developers use to decide how to create and when to create and how many to create.

Have a nice day otherwise have a tight sleep.