Tuesday, February 12, 2013

Different ways to create objects in Java


There are four different waysto create objects in java:

1. Using new keyword
This is the most common way to create an object in java.

MyObject object = new MyObject();

2. Using Class.forName()


MyObject object = (MyObject) Class.forName("com.MyTest").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();
Now you know how to create an object. But its advised to create objects only when it is necessary to do so.

5.Using Reflection

this.getClass().getClassLoader().loadClass("com.MyTest").newInstance();

No comments: