What are different ways to create objects in Java?

There are four different ways to create objects in java:
1. By using new keyword
This is the most common way to create an object in java. Almost 99% of objects are created in this way.

MyObject obj = new MyObject();

2. By 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 obj = (MyObject) Class.forName("org.mahi.MyObject").newInstance();

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

MyObject obj = new MyObject();
MyObject clonedObj = (MyObject) obj.clone();

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

ObjectInputStream ois = new ObjectInputStream(anInputStream );
MyObject obj = (MyObject) ois.readObject();

Author: Mahesh

Technical Lead with 10 plus years of experience in developing web applications using Java/J2EE and web technologies. Strong in design and integration problem solving skills. Ability to learn, unlearn and relearn with strong written and verbal communications.