Wednesday, April 27, 2022

Number Of Ways To Create Object In Java

Question:  How many Ways to Create an Object in Java?

Answer: We can create an object in java with 6 different ways which are mention below:

  1. Using new keyword.
  2. Using Class.newInstance() method.
  3. Using newInstance() method of constructor class.
  4. Using Object.clone() method.
  5. Using deserialization.
  6. Using factory method.

Suppose we have user class.

package com.javaiq.in.user;

public class User {

	int id;
	String name;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

}

Method 1 : Using new keyword.

This is the mostly used and common way of create an object in java of a class. By using the new keyword, we can call any type of constructor of the class which is, either the parameterized constructor or non-parameterized constructor.

User userObj = new User();

Method 2: Using new keyword.

Method 4: Using Object.clone() method.

To clone object we have to implements Cloneable interface and override clone() method in User class.

As we know clone() method returns Object so we have to cast to User class.

package com.javaiq.in.user;

public class User implements Cloneable {

	int id;
	String name;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	@Override
	public Object clone() throws CloneNotSupportedException {
		return super.clone();
	}

	@Override
	public String toString() {
		return "User [id=" + id + ", name=" + name + "]";
	}

}
package com.javaiq.in.user;

public class MainObjectTest {

	public static void main(String[] args) throws ClassNotFoundException, CloneNotSupportedException {
		// get the Class instance using new Operator
		User object = new User();
		object.setId(1);
		object.setName("User1");
		System.out.println("HashCode of User Object :" + object.hashCode());

		// clone of object
		User cloneObject = (User) object.clone();
		System.out.println("Clone of User Object :" + cloneObject);
		System.out.println("HashCode of Clone Object :" + cloneObject.hashCode());

	}

}

Output:

HashCode of User Object :1829164700
Clone of User Object :User [id=1, name=User1]
HashCode of Clone Object :2018699554

Method 5 : Using Object Deserialization.

To Serializ and Deserializ object we have to implements Serializable.

package com.javaiq.in.user;

import java.io.Serializable;

public class User implements Serializable {

	int id;
	String name;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	@Override
	public String toString() {
		return "User [id=" + id + ", name=" + name + "]";
	}

}
package com.javaiq.in.user;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class MainObjectTest {

	public static void main(String[] args) throws ClassNotFoundException, CloneNotSupportedException {
		// get the Class instance using new Operator
		User object = new User();
		object.setId(1);
		object.setName("User1");
		System.out.println("HashCode of User Object :" + object.hashCode());

		/* ############## Serialization process ############## */
		try {
			FileOutputStream file = new FileOutputStream("UserData.ser"); // writing an object in the file
			ObjectOutputStream out = new ObjectOutputStream(file);
			out.writeObject(object); // serialize object
			out.close(); // closes the ObjectOutputStream
			file.close(); // closes the file
			System.out.println("Object serialized Succsfuly.");
		} catch (IOException e) {
			e.printStackTrace();
		}
		User obj = null;
		/* ############## Deserialization process ############## */
		try {
			FileInputStream file = new FileInputStream("UserData.ser"); // reading an object from a file
			ObjectInputStream is = new ObjectInputStream(file);
			obj = (User) is.readObject(); // deserialize object
			is.close(); // closes the ObjectInputStream
			file.close(); // closes the file
			System.out.println("Object deserialized Succsfuly : " + obj);
			System.out.println("HashCode of User Object :" + obj.hashCode());
		} catch (IOException e) {
			System.out.println("IOException is caught");
		} catch (ClassNotFoundException e) {
			System.out.println("ClassNotFoundException is caught");
		}
	}

}

Output: This is clear from output, as hashcode is different from actual object to deserializ object. So its always create new object.

HashCode of User Object :1829164700
Object serialized Succsfuly.
Object deserialized Succsfuly : User [id=1, name=User1]
HashCode of User Object :295530567

No comments:

Post a Comment