How many ways an object can be created in java
While writing any java program, we generally use a new operator to create java objects and that is good practice too. However, we need to know other ways of creating objects which are very much needed in other instances.
1. Using new keyword
Employee emp1 = new Employee();
2. Using newInstance() method of Class
Employee emp2 = (Employee) Class.forName("com.personal.practice.Employee") .newInstance();
It can also be written as
Employee emp2 = Employee.class.newInstance();
3. Using newInstance() method of Constructor
Constructor constructor = Employee.class.getConstructor(); Employee emp3 = constructor.newInstance();
4. Using clone() method
Employee emp4 = (Employee) emp3.clone();
5. Using deserialization
ObjectInputStream in = new ObjectInputStream(new FileInputStream("data.obj")); Employee emp5 = (Employee) in.readObject();
Yes. We can create objects in 5 different ways those are using with new keywords and newInstance() include a constructor call but the other two clone and deserialization methods create objects without calling the constructor.
However one can argue that creating through an array, through string object, through Runtime class, through JNI, through varargs (...), autoboxing, lambda, etc.. is also a way of creating the object but these things are more specific to some classes only and handled directly by JVM, while we can create an object of any class by using these 5 ways.