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(
			"com.javahonk.createobject.CreateObjectTest")
			.newInstance();
	System.out.println("Create using reflection 1: "+cTest2);

	//or
	Class<? extends CreateObjectTest> class1=cTest2.getClass();
	CreateObjectTest cTest3 =  (CreateObjectTest) class1
			.newInstance();
	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);   
	oos.writeObject(cTest);
	oos.close();

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

	} catch (InstantiationException e) {
		e.printStackTrace();
	} catch (IllegalAccessException e) {
		e.printStackTrace();
	} catch (ClassNotFoundException e) {
		e.printStackTrace();
	} catch (FileNotFoundException e) {
		e.printStackTrace();
	} catch (IOException e) {
		e.printStackTrace();
	}

	}

	public CreateObjectTest cloneObject() throws CloneNotSupportedException {

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

	}

}

 

Output:


What are different ways to create object

Leave a Reply

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