Object Creation in Java – Different Ways / Methods

Get Job-ready: Java Course with 45+ Real-time Projects! - Learn Java

Java is an object-oriented language. A major concept of an OOP language is an object. An object helps access, name and operate a program easily. In this article, we will look at different ways of object creation in java. We know that class is just a blueprint of a program. It does not have any physical significance of its own. The physical entity of a class is an object. Whenever we instantiate an object, only after that memory is assigned to it.

What is an Object in Java?

In one word, an object is an instance of a class. We all know that a class does not have a physical significance of its own, the object represents the real word entity of the class. An object has attributes or properties and behaviour or methods. A class doesn’t have a memory of its own, as it does not have a physical state, whenever we instantiate an object of that class, memory is allocated depending on the attributes.

Characteristics of an object:

An object mainly has three characteristics:

  • State: The values stored in an object are known as the state of the object.
  • Behaviour: The behaviour of an object represents the functions performed by the object. They are mainly the methods present in that object.
  • Identity: Each object has a special ID or short name, that is used to call the methods present in the object. This unique ID is known as the identity of the object. It is known only to the programmer, not the end-user.

Various techniques of object creation in java:

There are a total of five different methods using which we can instantiate an object. They are as follows:

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

Let us understand each of these methods individually.

1. Using the new keyword:

The new keyword is the most common technique used to instantiate an object. The new keyword calls the constructor of the object and creates a new instance of the class.

Syntax:

ClassName ObjectName = new Class Name();

Code to understand object creation with the new keyword:

package com.DataFlair.ObjectCreation;
public class NewKeyword
{
    void show()    
    {    
        System.out.println("DataFlair");    
    }    
    public static void main(String[] args)   
    {     
        NewKeyword obj = new NewKeyword();//object creation   
        obj.show();//Calling method that is part of the object
    }    
}

The output of the above code:

DataFlair

2. Using newInstance() Method of Class class:

The newInstance() method of the Class class calls the default constructor to create the object. The method returns the newly created instance of the class of which the object is a part. The newInstance() method is part of the Constructor class.

Syntax:

public T newInstance() throws InstantiationException, IllegalAccessException  

The method throws the following exceptions:

  • IllegalAccessException
  • InstantiationException
  • ExceptionInInitializerError

We can create an object in the following ways:

  • ClassName object = ClassName.class.newInstance();
  • ClassName object = (ClassName) Class.forName("Name of Full Class").newInstance();

The forName() method is a static method which takes className as a parameter and returns the object of the class. It just loads the class to the program but does not create an object. If the class cannot be loaded it gives a ClassNotFoundException and a LinkageError if the linkage has failed.

The newInstance() method only works if the class has a public default constructor.

Code to create object using newInstance() Class class:

package com.DataFlair.ObjectCreation;
public class InstanceMethodClass
{
  String name = "DataFlair";
  public static void main(String[] args)
  {
    try
    {
      Class obj1 = Class.forName("com.DataFlair.ObjectCreation.InstanceMethodClass");
      InstanceMethodClass obj =(InstanceMethodClass) obj1.newInstance();
      System.out.println(obj.name);
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
  }
}

The output of the above code:

DataFlair

3. Using newInstance() Method of Constructor class:

This method is similar to the previous method. It is also known as a reflective way to create an object. The method is defined in the Constructor class of java.lang.reflect package. Unlike the previous method, here we can use parameterized constructors as well as private constructors. This is the reason why this method is preferred over the Class class newInstance() method.

Syntax:

Public T newInstance(Object... initargs) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException  

The newInstance() method passes an array of objects as an argument. It returns a newly created object by calling the constructor of the class.

The method throws the following exceptions:

  • IllegalAccessException
  • IllegalArgumentException
  • InstantiationException
  • InvocationTargetException
  • ExceptionInInitializerError

Syntax of creating object:

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

Code to create object using Constructor class newInstance() method:

package com.DataFlair.ObjectCreation;
import java.lang.reflect.*;
public class InstanceMethodConstructor
{
  private String name;
  public void Name(String name)
  {
    this.name = name;
  }
  public static void main(String[] args)
    {
    try
    {
      Constructor<InstanceMethodConstructor> constructor = InstanceMethodConstructor.class.getDeclaredConstructor();
      InstanceMethodConstructor obj = constructor.newInstance();
      obj.Name("DataFlair");
      System.out.println(obj.name);
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
  }
}

The output of the above code:

DataFlair

4. Using the clone() Method:

The clone() method is present inside the Object class. It can create a copy of a preexisting object and return it. It copies the previous object’s properties into the newly created object. The clone() method doesn’t call the constructor. If the object to be copied does not support a cloneable interface, the method will throw CloneNotSupportedException.

Syntax:

protected Object clone() throws CloneNotSupportedException  

Creating a new object from old object:

ClassName newobjectname = (ClassName) oldobjectname.clone();  

Code to create a new object using clone() method:

package com.DataFlair.ObjectCreation;
public class CloneMethod implements Cloneable
{
  @Override
  protected Object clone() throws CloneNotSupportedException
  {
    return super.clone();
  }
  String name = "DataFlair";
  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();
    }
  }
}

The output of the above code:

DataFlair

5. Using Deserialization:

Serialization in java means, to convert an object into a sequence of byte-stream. The reverse of serialization is deserialization. The JVM creates an object whenever we deserialize an object. It does not use a constructor to create objects. To use deserialization, the serialization interface must be implemented at first.

Syntax:

Serialization:

public final void writeObject(object x) throws IOException

Deserialization:

public final Object readObject() throws IOException,ClassNotFoundException

 

using deserialization

First, we create a class with a serialization interface, so that its object can be serialized and deserialized.

Serialization interface enabled class:

package com.DataFlair.ObjectCreation;
import java.io.Serializable;
public class Intern implements Serializable
{
    int Internid;    
    String InternName;    
    public Intern(int Internid, String InternName)   
    {    
       this.Internid = Internid;    
       this.InternName = InternName;    
    }    
}

Serialization of Object of the Intern Class:
We will serialize an object of the Intern class by using the writeObject() method of the ObjectOutputStream class. The object state will be saved into the interns.txt file.

Code to serialize an object of the Intern Class:

package com.DataFlair.ObjectCreation;
import java.io.*;
public class Serialization
{
    public static void main(String args[])  
    {    
        try  
        {        
            Intern I = new Intern(1,"Arka Ghosh");  
            FileOutputStream fout=new FileOutputStream("interns.txt"); 
            ObjectOutputStream out=new ObjectOutputStream(fout);    
            out.writeObject(I);    
            out.flush();       
            out.close();    
            System.out.println("Created text file successfully!!!");    
        }  
        catch(Exception e)  
        {  
            System.out.println(e);  
        }    
    }    
}

The output of the above code is:

Created text file successfully!!!

Deserialization of the object of Intern Class:
We use the readObject() method of the ObjectInputStream class to deserialize the object.

Code to Deserialize the serialized object:

package com.DataFlair.ObjectCreation;
import java.io.*;
public class Deserialization
{
    public static void main(String args[])  
    {    
        try  
        {    
            ObjectInputStream in=new ObjectInputStream(new FileInputStream("interns.txt"));
            Intern I1=(Intern)in.readObject();
            System.out.println("Intern ID and Name is:");
            System.out.println(I1.Internid+" "+I1.InternName);        
            in.close();    
        }  
        catch(Exception e)  
        {  
        System.out.println(e);  
        }    
    }    
}

The output of the above code:

Intern ID and Name is:
1 Arka Ghosh

Conclusion:

So, we saw in this article, how objects can be created using so many different methods. Creating an object is very essential, as it is required in almost every program to make the program readable. That is why it is very important to know the different ways to create an object.

If you are Happy with DataFlair, do not forget to make us happy with your positive feedback on Google

courses

Leave a Reply

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