Object Creation in Java – Different Ways / Methods

1. Objective

In our last tutorial, we discussed Java Annotations. Here, in this Object Creation in Java tutorial, we are going to study about how to create object in Java with example problem. In addition, we will discuss Object Creation in Java Programming Language in different ways/methods.

So, let us start Object Creation in Java.

Object Creation in Java

Object Creation in Java – Different Ways to Create Objects in Java

2. Object Creation in Java

An object is created by a class in Java, a class is basically a blueprint for objects. There are many ways/methods to create an object in Java. Let us study them.

Let’s See Classes and objects in Java with real-time example programmers

3. Different Ways to Create Objects in Java

Below, we discuss some ways for Object Creation in Java.

a. Using new Keyword

Utilizing new keyword is an essential approach to make an object. This is the most well-known approach to make a question in Java. Just about 99% of items are made along these lines. By utilizing this technique we can call any constructor we need to call (no argument or parameterized constructors).

Example –

public class NewKeywordExample
{
    String name = "dataflair";
    public static void main(String[] args)
    {
        NewKeywordExample obj = new NewKeywordExample();
        System.out.println(obj.name);
    }
}

Let’s Learn Constructor in Java and Its Types

b. Using New Instance

In the event that we know the name of the class and on the off chance that it has an open default constructor we can make a protest – Class.forName. We can utilize it to make the Object of a Class. Class.forName really stacks the Class in Java yet doesn’t make any Object. To Create an Object of the Class you need to utilize the new Instance Method of the Class.

Example –

public class NewInstanceExample
{
    String name = "dataflair";
    public static void main(String[] args)
    {
        try
        {
            Class cls = Class.forName("NewInstanceExample");
            NewInstanceExample obj =
                    (NewInstanceExample) cls.newInstance();
            System.out.println(obj.name);
        }
        catch (ClassNotFoundException e)
        {
            e.printStackTrace();
       }
        catch (InstantiationException e)
        {
            e.printStackTrace();
        }
        catch (IllegalAccessException e)
        {
            e.printStackTrace();
        }
    }
}

c. Using Clone() Method

At whatever point clone() is approached any object, the JVM really makes another question and duplicates all substance of the past question into it. Making an object utilizing the clone technique does not conjure any constructor.

Do You Know How Inheritance in Java is used

To utilize clone() strategy on a protest we have to actualize Cloneable and characterize the clone() method in it.

Example –

public class CloneExample implements Cloneable
{
    @Override
    protected Object clone() throws CloneNotSupportedException
    {
        return super.clone();
    }
    String name = "Dataflair";
    public static void main(String[] args)
    {
        CloneExample obj1 = new CloneExample();
        try
        {
            CloneExample obj2 = (CloneExample) obj1.clone();
            System.out.println(obj2.name);
        }
        catch (CloneNotSupportedException e)
        {
            e.printStackTrace();
        }
    }
}

Note –

  • Here we are making the clone of a current Object and no new Object.
  • A class needs to execute Cloneable Interface else it will toss CloneNotSupportedException.

d. Using Deserialization

Whenever we serialize and after that deserialize an object, JVM makes a different object. In deserialization, JVM doesn’t utilize any constructor to make the question.

Read More about Serialization and Deserialization in Java

To deserialize a question we have to execute the Serializable interface in the class.

Example for Serializing an Object:

import java.io.*;
class DeserializationExample implements Serializable
{
    private String name;
    DeserializationExample(String name)
    {
        this.name = name;
    }
    public static void main(String[] args)
    {
        try
        {
            DeserializationExample d =
                    new DeserializationExample("Dataflair");
            FileOutputStream f = new FileOutputStream("file.txt");
            ObjectOutputStream oos = new ObjectOutputStream(f);
            oos.writeObject(d);
            oos.close();
            f.close();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}

Example for Deserialization of Object:

import java.io.*;
public class DeserializationExample
{
    public static void main(String[] args)
    {
        try
        {
            DeserializationExample d;
            FileInputStream f = new FileInputStream("file.txt");
            ObjectOutputStream oos = new ObjectOutputStream(f);
            d = (DeserializationExample)oos.readObject();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        System.out.println(d.name);
    }
}

Let’s Explore Java String, Methods And Constructor – Syntax and Example

e. Using newInstance() method of Constructor class

This is like the newInstance() technique for a class. There is one newInstance() technique in the java.lang.reflect.Constructor class which we can use to make objects. It can likewise call a parameterized constructor, and private constructor by utilizing this newInstance() technique.

Both newInstance() techniques are known as intelligent approaches to make objects. Truth be told newInstance() technique for Class inside utilizations newInstance() strategy for Constructor class.

Example –

import java.lang.reflect.*;
public class ReflectionExample
{
    private String name;
    ReflectionExample()
    {
    }
    public void setName(String name)
    {
        this.name = name;
    }
    public static void main(String[] args)
    {
        try
        {
            Constructor<ReflectionExample> constructor
                = ReflectionExample.class.getDeclaredConstructor();
            ReflectionExample r = constructor.newInstance();
            r.setName("GeeksForGeeks");
            System.out.println(r.name);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}
So, this was all about Object Creation in Java Tutorial. Hope you like our explanation.

4. Conclusion

Hence, in this tutorial, we learned different ways for Object Creation in Java with examples Program. Furthermore, if you have any query feel free to ask in the comment section.

Related Topic- 7 Unknown Facts about Java Null 

For reference 

Leave a Reply

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