This question generally ask in the interview to check the basic of core java. In real life purpose of all the type of creating object are 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.
There are four different ways to create objects in java
- . Using new keyword
- Using Class.forName()
- Using clone()
- Using object Deserialization
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();
Question is why we required to create an object using
Class.forName(), usually if class is not loaded in our jvm, and you want to load at run time, any third party class, from 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();
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 use this in prototype design creational design pattern.
MyClazz myClazz = new MyClazz(); MyClazz anotherObject = (MyClazz) myClazz.clone();
deserialization is nothing but creating an object from its serialized form.
ObjectInputStream inStream = new ObjectInputStream(anInputStream ); MyClazz object = (MyClazz) inStream.readObject();
Now you know how to create an object. Preference is yours choice but be careful how to create and what scenario we choose what option.
If any suggestion please write comment , will modify accordingly.