Thursday, 6 July 2017

Different ways to create an object In Java

Below are the different ways to create an object in java.

1. using new keyword
2. using newInstance() method of class Class
3. using newInstance() method of class Constructor
4. using clone() method
5. using deserialization

Using new keyword:

1. Employee emp = new Employee();

Using newInstance() method of class Class:

1. Employee emp2 = Class.forName("Employee").newInstance();
2. Employee emp3 = Employee.class.newInstance();

Using newInstance() method of class Constructor:

1. Constructor empConstructor = Employee.class.getConstructor(); 
Employee emp4 = empConstructor.newInstance()

Using clone() method:

1. Calling clone() method, actually creates a new object and copies all the contents of old object into it. Creating an object using clone method doesn't invoke any constructor.
2. To use clone() method on an object, we need to implement Cloneable interface and define clone() method in it.

Employee emp5 = (Employee) emp4.clone();

Using deserialization:

1. when ever we serialize or deserialize an object, the JVM creates a separate object for us. JVM doesn't use any constructor to create the object.
2. To deserialize an object we need to implement a Serializable interface in our class.

ObjectInputStream in = new ObjectInputStream(new FileInputStream("data.obj"));
Employee emp6 = (Employee) in.readObject();

You can get the clear explanation in the following link



Post a Comment

Note: only a member of this blog may post a comment.