What are different ways to create object

What are different ways to create object ?

Answer : Different ways to create object mentioned below: 

  • Use new keyword
  • Use clone
  • Use reflection
  • Use object serialization and de-serialization

Please see example below:

package com.javahonk.createobject;

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

public class CreateObjectTest implements Cloneable,Serializable{

	private static final long serialVersionUID = 1L;
	private static ObjectInputStream inStream;

	public static void main(String[] args) 
			throws CloneNotSupportedException {

	try {

	// Create object using new
	CreateObjectTest cTest = new CreateObjectTest();
	System.out.println("Create using new: "+cTest);

	// Create an object using clone
	CreateObjectTest cloneTest = new CreateObjectTest();
	cloneTest = cloneTest.cloneObject();
	System.out.println("Create object using clone: "+cloneTest);

	// Create object through reflection
	CreateObjectTest cTest2 = (CreateObjectTest) Class.forName(
	System.out.println("Create using reflection 1: "+cTest2);

	Class<? extends CreateObjectTest> class1=cTest2.getClass();
	CreateObjectTest cTest3 =  (CreateObjectTest) class1
	System.out.println("Create using reflection 2: "+cTest3);

	// Create an object using de-serialization

	//Write object to file
	FileOutputStream fout = new FileOutputStream("c:\\Test.txt");
	ObjectOutputStream oos = new ObjectOutputStream(fout);   

	//Read object from file
	FileInputStream fis = new FileInputStream("c:\\Test.txt");
	inStream = new ObjectInputStream(fis );
	CreateObjectTest cTest4 = (CreateObjectTest) inStream
	System.out.println("Create using de-serialization: "+cTest4);

	} catch (InstantiationException e) {
	} catch (IllegalAccessException e) {
	} catch (ClassNotFoundException e) {
	} catch (FileNotFoundException e) {
	} catch (IOException e) {


	public CreateObjectTest cloneObject() throws CloneNotSupportedException {

		CreateObjectTest cloneTest = (CreateObjectTest) super.clone();
		return cloneTest;





What are different ways to create object

Leave a Reply

Your email address will not be published. Required fields are marked *

I am not Robot *