Create Object In Java

In Java, we can create objects of a class in multiple ways. As we know, a class serves as a blueprint for objects, and we create objects based on that blueprint. This concept is often overlooked or underrated by programmers but can be beneficial. Understanding and utilizing this concept can be advantageous, and it may even be asked about in interviews to assess a programmer’s knowledge.

Get ready to dive into the exciting world of Java object creation! In this engaging tutorial, we will explore the process of creating objects in Java and bring the concepts with practical examples. At the end of this tutorial, you’ll have a solid understanding of How to create objects in Java and be ready to apply this knowledge to your projects. So, let’s get started and unlock the power of object creation in Java!

Various ways to create Object in Java

In Java, there are various ways to create objects. This article will explore and discuss each of these methods individually. We will use programs to illustrate how these methods work internally and provide a clear understanding of how to create objects in Java. So, let’s dive in and explore the different ways to create objects in Java, one by one!

  • Using a new operator or keyword
  • Using the clone method of the Object class
  • Using Object De-serialization
  • Using Reflection API

Let us move forward and discuss all possible ways to create an object in Java.

Using the new operator or keyword

The simplest and most common way to create an object in Java is by using the “new” keyword. This method covers almost 99% of object creation in Java. With the “new” keyword, we can call any constructor we need, whether it’s a constructor with no arguments or one that requires parameters. This straightforward approach allows us to create objects easily and efficiently.

Program: Write a Java Program to create an object using a new keyword.

package com.softwaretestingo.objects;
public class CreateObjectEx1 
{
	public static void main(String[] args) 
	{
		// Way 1: using new operator or keyword
		CreateObjectEx1 obj=new CreateObjectEx1();
	}
}

Using a clone() Method of Object class

When we call the clone() method on an object in Java, the JVM creates a new object and copies all the contents of the original object into it. Creating an object using the clone method does not involve invoking any constructors. However, in order to use the clone() method on an object, we must implement the Cloneable interface and define the clone() method within the class. This allows us to create a copy of the object using the clone() method.

Method signature :

protected native Object clone() throws CloneNotSupportedException;
package com.softwaretestingo.objects;
public class CreateObjectEx2  implements Cloneable
{

	public static void main(String[] args) throws CloneNotSupportedException 
	{
		// Way 1: using new operator or keyword
		CreateObjectEx2 obj=new CreateObjectEx2();

		// Way 2: using clone() method of Object class
		CreateObjectEx2 obj1 = (CreateObjectEx2)obj.clone();

		// invoking display() method
		obj1.display();
	}
	
	//display() method to test
	public void display()
	{
		System.out.println("display() method is invoked");
	}
}

Output:

display() method is invoked

Things to consider while creating an Object using the clone method:

If the class is not implemented in the Cloneable interface, you will get CloneNotSupportedException.

Using de-serialization

When we serialize an object and then deserialize it in Java, the JVM creates a new object separately. During deserialization, the JVM uses no constructor to create the object. To successfully deserialize an object, we must implement the Serializable interface in the class. This allows the object to be serialized and deserialized properly, ensuring a new object is created during the deserialization process.

Student.Java

package com.softwaretestingo.objects;
import java.io.Serializable;
public class Student implements Serializable
{
	public String name;
	public int id;

	public void mailCheck() 
	{
	}
}

Serialization.Java

package com.softwaretestingo.objects;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
public class Serialization 
{
	public static void main(String[] args) 
	{
		Student sd=new Student();
		sd.name="Ramesh";
		sd.id=101;

		try
		{
			FileOutputStream fileOut = new FileOutputStream("student.ser");
			ObjectOutputStream out = new ObjectOutputStream(fileOut);
			out.writeObject(sd);
			out.close();
			fileOut.close();
			System.out.printf("Serialized data is saved in student.ser");
		} 
		catch (IOException i)
		{
			i.printStackTrace();
		}
	}
}

Deserialization.java

package com.softwaretestingo.objects;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
public class Deserialization 
{

	public static void main(String[] args) 
	{
		Student sd = null;
		try
		{
			FileInputStream fileIn = new FileInputStream("student.ser");
			ObjectInputStream in = new ObjectInputStream(fileIn);
			sd = (Student) in.readObject();
			in.close();
			fileIn.close();
		} catch (Exception ex)
		{

			System.out.println("Employee class not found");
			ex.printStackTrace();
			return;
		}
		System.out.println("Deserialized Employee...");
		System.out.println("Name: " + sd.name);
		System.out.println("Id: " + sd.id);
	}
}

Output:

Deserialized Employee...
Name: Ramesh
Id: 101

Explanation:

  • Assume that the Student object is serialized in the ” student ” file.ser”
  • The above program depicts the steps to de-serialize an Object (i.e., de-serializing from file storage in binary format into Java’s heap memory)
  • This statement sd = (Student) in.readObject();, which reads the object’s state and re-creates a new object
  • This way, a new Object can be created in Java using the Object de-serialization process.

Avatar for Softwaretestingo Editorial Board

I love open-source technologies and am very passionate about software development. I like to share my knowledge with others, especially on technology that's why I have given all the examples as simple as possible to understand for beginners. All the code posted on my blog is developed, compiled, and tested in my development environment. If you find any mistakes or bugs, Please drop an email to softwaretestingo.com@gmail.com, or You can join me on Linkedin.

Leave a Comment