Java Object Creation – Learn to Create Objects with Different Ways

We know that an object is an identifiable entity which is an instance of the class. Today this article will guide you on Object Creation in Java in different ways. We know that without creating and instantiating object there is no use of creating a class.

A class does not occupy a memory while we create it. The memory is allocated to it only when we create its object. In Java, object creation is not limited to a single way, but there are several ways to create it. So without any further delay let’s start exploring the ways to create an object.

First, it is recommended for you to take a quick revision of Classes and Objects in Java with Techvidvan to clear your basis.

What is an Object?

An object is a real-world entity that has some characteristics and behavior. For example, in real-life a car is an object which has characteristics like brand name, color, engine type, average, etc, and attributes like drive, brake, stand. The objects in Java programming are similar to the real-life objects that have attributes (properties) and behavior (methods or functions).

Characteristics of an Object

We can define an object by three characteristics:

  • State: The state of an object represents the value stored in the object.
  • Behavior: The behavior of an object represents functionality performed by an object. For example, running, sitting, etc.
  • Identity: The identity of an object is represented by a unique ID. The JVM internally uses this unique ID to identify the object uniquely. And, this unique ID is not visible to the external user.

Java Object Creation

In Java, we can create objects with 6 different methods which are:

  • By new keyword
  • By newInstance() method of Class class
  • By newInstance() method of constructor class
  • By clone() method
  • By deserialization
  • By factory method

Let’s start discussing each method of creating an object with examples.

1. Java Object Creation by new keyword

It is the most simple and common way of creating an object of a class. By using the new keyword, we can call any type of constructor of the class that is, either the parameterized constructor or non-parameterized constructor.

Dive a little deep into the concept of Java Constructor with Techvidvan.

Let’s see the syntax to create an object using the new keyword:

ClassName ObjectName = new ClassName();

Code to create an object using the new keyword :

package com.techvidvan.objectcreation;
public class NewKeyword
{
  String name = "TechVidvan Java Tutorial";
  public static void main(String[] args)
  {
    //Creating object using new keyword
    NewKeyword obj = new NewKeyword();

    //Accessing the class variable using the object
    System.out.println(obj.name);
  }
}

Output:

TechVidvan Java Tutorial

2. Java Object Creation by newInstance() method of Class class

This is another technique to create an object of the class. We use the newInstance() method of a Class class to create an object. This newInstance() method calls the no-arg constructor of the class to create the object.

Syntax to create an object by a newInstance() of Class:

Class cls = Class.forName("ClassName");
ClassName objectName = (ClassName) cls.newInstance();

Code to create an object using the newInstance() method of Class:

package com.techvidvan.objectcreation;
public class NewInstanceMethod
{
  String name = "TechVidvan Java Tutorial";
  public static void main(String[] args)
  {
    try
    {
      Class cls = 					   Class.forName("com.techvidvan.objectcreation.NewInstanceMethod");
      NewInstanceMethod obj =(NewInstanceMethod) cls.newInstance();
      System.out.println(obj.name);
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }

  }
}

Output:

TechVidvan Java Tutorial

3. Java Object Creation by newInstance() method of Constructor class

We can also use the newInstance() method of java.lang.reflect.Constructor class to create an object. The newInstance() method of the Constructor class is similar to the newInstance() method of the Class class.

Syntax of using newInstance() method of Constructor class:

Constructor<ClassName> constructor = ClassName.class.getConstructor();
ClassName objectName = constructor.newInstance();

Code to create an object using the newInstance() method of Constructor:

package com.techvidvan.objectcreation;
import java.lang.reflect.*;
public class NewInstanceMethod
{
  private String name;
  public void setName(String name)
  {
    this.name = name;
  }
  public static void main(String[] args)
    {
    try
    {
      Constructor<NewInstanceMethod> constructor = 					 
                        NewInstanceMethod.class.getDeclaredConstructor();
      NewInstanceMethod obj = constructor.newInstance();
      obj.setName("TechVidvan Java Tutorial");
      System.out.println(obj.name);
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
  }
}

Output:

TechVidvan Java Tutorial

4. Java Object Creation by clone() method

When we call the clone() method through an object, the Java compiler automatically creates a new object of that class. JVM actually copies all content of the older object into the newly created object.

To use the clone() method on an object we have to implement the Cloneable interface and override the clone() method in our class.

WAIT! It’s the right time to get familiar with the concept of Method Overriding in Java.

Syntax of using the clone() method to create an object:

ClassName object1 = new ClassName();
ClassName object2 = (ClassName) object1.clone();

Code to create an object using the clone() method:

package com.techvidvan.objectcreation;
public class CloneMethod implements Cloneable
{
  @Override
  protected Object clone() throws CloneNotSupportedException
  {
    return super.clone();
  }
  String name = "TechVidvan Java Tutorial";
  public static void main(String[] args)
  {
    CloneMethod obj1 = new CloneMethod();
    try
    {
      CloneMethod obj2 = (CloneMethod) obj1.clone();
      System.out.println(obj2.name);
    }
    catch (CloneNotSupportedException e)
    {
      e.printStackTrace();
    }
  }
}

Output:

TechVidvan Java Tutorial

5. Java Object Creation using deserialization

When we serialize an object and then deserialize it, JVM creates a new object. To deserialize an object, we need to implement the java.io.Serializable.

Create Employee.java

package com.techvidvan.objectcreation;
public class Employee implements java.io.Serializable
{
  public String name;
  public int id;

  public void mailCheck() {
  }

}

Code to serialize an object:

package com.techvidvan.objectcreation;
import java.io.*;
public class Serialization
{
  public static void main(String [] args)
  {
    Employee e = new Employee();
    e.name = "Ayush Verma";
    e.id=101;

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

Output:

Serialized data is saved in /tmp/employee.ser

Code to deserialize an object:

package com.techvidvan.objectcreation;
import java.io.*;
public class Deserialization
{
  public static void main(String [] args)
  {
    Employee e = null;
    try
    {
      FileInputStream fileIn = new 			FileInputStream("/tmp/employee.ser");
      ObjectInputStream in = new ObjectInputStream(fileIn);
      e = (Employee) 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: " + e.name);
    System.out.println("Id: " + e.id);
  }
}

Output:

Deserialized Employee…
Name: Ayush Verma
Id: 101

Summary

An object is a real-time entity that shows its characteristics and behavior. We learned different ways to create an object of a class in Java. The most commonly used method of creating an object is the new operator, but there are many more techniques to create an object. We discuss all the ways of creating an object with the help of syntax and examples.

Thank you for reading our article. Do share your feedback through the comment section below.

Keep Learning 🙂

1 Response

  1. Vishal says:

    Very well written article!!Thanks for great information on instantiation!

Leave a Reply

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

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.