Different ways to create an/a object in java - Java @ Desk

Thursday, June 27, 2013

Different ways to create an/a object in java

In java, an object of a class can be created in various ways. This is the most important as well as most common question asked in java interviews. There are 4 difference ways to create a/an object in java as described below:

1) Using new keyword
2) Using Class.forName()
3) Using clone()
4) Using object deserialization
Detailed explanation on different ways to create a object in java:

Consider a class as shown below:

 public class WaysToCreateObject implements Cloneable {  
   public static void main(String args[]) throws InstantiationException, IllegalAccessException,  
       ClassNotFoundException, CloneNotSupportedException {  
     // Object created using the new keyword  
     WaysToCreateObject objectNew = new WaysToCreateObject();  
     // Object created using Class.forName  
     WaysToCreateObject objectClassForName = (WaysToCreateObject) Class.forName(  
         "com.objectcreation.WaysToCreateObject").newInstance();  
     // Object created using clone  
     WaysToCreateObject objectClone = (WaysToCreateObject) objectNew.clone();  
   }  
 }  
To read the complete post click below


As shown above, 1) Using new keyword : This is the most common and most used way to create a java object. Maximum java programmers use the new keyword to create a new object. Most simplest way. This way is also called as static instance creation of an object.

2) Using Class.forName() : This way can be used, if the programmer knows the class name along with the package of the class. If you use this way, then the class must handle throws InstantiationException, IllegalAccessException, ClassNotFoundException.
Most important thing that the programmer needs to handle here is to check if the object created using this way do not have private constructor.

3) Using clone() : This way ob object creation is done using clone() method of an object. Using this, the method gets created which is a duplicate copy of an original copy. All the properties gets copied in the new object.
Most important thing when we create an object using this way is that the class must implement Cloneable interface, otherwise it will throw CloneNotSupportedException. Also the class must throw CloneNotSupportedException, in order to proper compilation of a java class.

4) Using object deserialization : This is done using the serialization/de-serialization in java. The object that is already serialized and is being stored somewhere, we need to de-serialize that object and get the object. This is being done as shown below

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






No comments:

Post a Comment