Different ways to create objects in java
1. Using the new keyword
It is the most common and regular way to create an object and actually very simple one also. By using this method we can call whichever constructor we want to call (no-arg constructor as well as parametrised). Employee emp1 = new Employee();
2. Using Class.newInstance() method
We can also use the newInstance() method of the Class class to create objects, This newInstance() method calls the no-arg constructor to create the object.We can create objects by newInstance() in following way.
Employee emp2 = (Employee) Class.forName("com.Employee").newInstance();
Or
Employee emp2 = Employee.class.newInstance();
3. Using newInstance() method of Constructor class
Similar to the newInstance() method of Class class, There is one newInstance() method in the java.lang.reflect.Constructor class which we can use to create objects. We can also call a parameterized constructor, and private constructor by using this newInstance() method.Both newInstance() methods are known as reflective ways to create objects. In fact newInstance() method of Class class internally uses newInstance() method of Constructor class. That's why the later one is preferred and also used by different frameworks like Spring, Hibernate, Struts etc.
Constructor<Employee> constructor = Employee.class.getConstructor();
Employee emp3 = constructor.newInstance();
4. Using clone() method
Whenever we call clone() on any object JVM actually creates a new object for us and copy all content of the previous object into it. Creating an object using clone method does not invoke any constructor.To use clone() method on an object we need to implements Cloneable and define clone() method in it.
Employee emp4 = (Employee) emp3.clone();
Java cloning is the most debatable topic in Java community and it surely does have its drawbacks but it is still the most popular and easy way of creating a copy of any object until that object is full filling mandatory conditions of Java cloning.
5. Using deserialization
Whenever we serialize and then deserialize an object JVM creates a separate object for us. In deserialization, JVM doesn’t use any constructor to create the object.To deserialize an object we need to implement the Serializable interface in our class.
ObjectInputStream in = new ObjectInputStream(new FileInputStream("data.obj"));
Employee emp5 = (Employee) in.readObject();