Different ways of creating object in Java

1. Using new keyword
This is the most common way to create an object in java.In This we will be using the new operator which will allocates the memory space and initialize the field with default value. Then it executes the code inside the specified constructor which normally re-writes the default values with the value inside the constructor.

 
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( vinay.abc.MyObject ).newInstance();

vinay.abc.MyObject – is the class name

3. Using clone()

The clone() can be used to create a copy of an existing object. Object.clone() is a native method which translates into instructions for allocating the memory and copying the data.Even if you override the clone method then also you need to call the super.clone() method inside the overridden clone method. In this method a copy instruction is called and which copy the data from original object to clone 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. It will uses the ‘new’ operator internally and always calls the default constructor.

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

5. Using class loader

one more is through creation of object using classloader
like

this.getClass().getClassLoader().loadClass( com.amar.myobject ).newInstance();

pimp it

Vinay

I am an Oracle ACE in Oracle ADF/Webcenter. Sr Java Consultant-working on Java/J2EE/Oracle ADF/Webcenter Portal/ content and Hibernate for several years. I'm an active member of the OTN JDeveloper/Webcenter forum. Passionate about learning new technologies. I am here to share my knowledge. Give your views and suggestion on [email protected] .

More Posts - Website

Follow Me:
TwitterLinkedInGoogle PlusYouTube