10/13/15

What are different ways to create new object in JAVA

Hi Readers,

Here I am writing few common ways to create new object in JAVA. Some ways are very frequent but some we rarely use, but it is good to know and keep in mind what are other ways to create object in Java Programming.

Using new keyword

This is the most common way to create an object in java programming. Almost 99% of objects are created in this way.

 MyObject object = new MyObject();


Using Class.forName() and get instance.

If we know the name of the class & if it has a public or default constructor, we can create an object in this way.

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

Class.forName will load the class and newInstance() method will give us new object.


Using clone() method from Object Class

The clone() can be used to create a copy of an existing object. We need to keep in mind that cloning will not invoke constructor.

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


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();

using reflection

example :-
 
 String.class.newInstance() will give you a new empty String object.