As we know that creation of an object in java is a cost-effective affair. Therefore we should have knowledge of different ways to create Objects in java so that we can use a particular way in the given scenario to handle the situation in a better way. Here we will find out 5 ways to create an object in Java.
Using new keyword :
This way of creating object in Java is the most common way in all.
Using newInstance() method of class ‘Class’ :
You must be aware of the Reflection API in Java. However, under reflection API we have these classes ‘Class’ & ‘Constructor’. Moreover, both classes have newInstance() method in it to create objects in Java. Therefore, we will see newInstance() method of class ‘Class’ in this section:
Using newInstance() method of class ‘java.lang.reflect.Constructor’:
Class.newInstance() can only invoke the zero-argument constructor, while Constructor.newInstance() may invoke any constructor, regardless of the number of parameters.
Using clone() method of class java.lang.Object:
clone() method creates and returns a copy of this object. In order to use clone() method class should implement Cloneable interface then it should implement clone() method accordingly. In this case, constructor of the class will not be called.
Using Deserialization :
The other way is to create an instance is by de-serializing the Object. We have to serialize the object before deserializing it as below:
However, we have seen 5 ways to create an object in Java. Furthermore, we have other ways like the one which is used by Spring Container for bean instantiation. Every java developer should know about creation of objects as we can’t stay tuned with java without knowing it. Additionally, we will extend the article if we find any other update in this topic. Please don’t hesitate to comment if you find any update on this topic.
For other important topics on Java/J2EE, kindly visit our blog.
Nice tutorial. I liked it.
Good one !
Nice Blog !