There are 4 different ways to create object in Java. Learn different ways by example: using new keyword, using Class.forName, cloning and deserializing. Learn various ways to create object in Java.
1. 4 different ways to create object in Java
There are four different ways of instantialting or creating objects in Java
- using new keyword
- using class.forName() method
- using clone() method
- using deserializing
The question: what are the different ways of creating objects in Java? Usually asked in Java interview to check the basic of Java. In real life, the purpose of all the types of creating objects is different. Usually when we required a object to call their function/method , we use new
operator , it means , when we call new Claszz()
it invoke default constructor. if you pass a parameter in new clazz(String a) it calls the respective parameterized constructor.
2. Create object using new keyword
Creating object with new keywords is most popular and elegant way in Java. This is the most common way to create an object in Java, when we required to access any method on it. You can say, approx 99% of objects are created via this way.
MyClazz myClazz = new MyClazz();
3. Create object using Class.forName()
The main question is why we required to create an object using Class.forName()
, usually if the class is not loaded in our JVM, and you want to load at run time, any third party class, from the third party jar file, we should go for this way. If we know the name of the class and if it has a public default constructor we can create an object in this way.
MyClazz object = (MyClazz) Class.forName("com.mysoftkey.MyClazz").newInstance();
4. Create object using clone() function
The clone()
can be used to create a copy of an existing object. There are 2 different variant of it , shallow copy and deep copy of it. Usually, we use this in prototype design creational design pattern.
MyClazz myClazz = new MyClazz(); MyClazz anotherObject = (MyClazz) myClazz.clone();
5. Create object using Deserialization
Object deserialization
is nothing but creating an object from its serialized form. So this is also one of the way of creating of an Object in java. example of deserialising as follows:
ObjectInputStream inStream = new ObjectInputStream(anInputStream ); MyClazz object = (MyClazz) inStream.readObject();
Now you know how to create an object. Preference is your choice but be careful how to create and what scenario we choose option.
6. Reference
I hope you enjoyed this post of 4 different ways of creating an object in Java. You can visit Core Java tutorial for more details
Visit oracle Java docs for Creating of a Java Object.
If any suggestion please write comment, I will modify accordingly.
Good