Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

How to Create Object in Java

Last Updated on March 31, 2023 by Prepbytes

A Class serves as a blueprint for an object, whereas an object is the class’s implementation. A class, for example, is equivalent to a house blueprint. You can create as many houses as you want with this blueprint. This article aims to discuss different ways of object creation in Java.

How to Create Object in Java?

An object is a fundamental building block in an OOPs language. We cannot run any Java program without first creating an object. Let’s see how we can create object in Java.

There are several different ways of object creation in Java:

1. Object Creation in Java Using new Keyword

This is the most common approach for creating an object. Almost all the objects are created using this method. The new keyword implicitly invokes the class’s constructor. The Constructor can be parameterized or non-parameterized. The new keyword allocates memory for the object and returns a reference to it.

Code Implementation:

class PrepBytes {
  public String name;
  PrepBytes() {
    name = "Hariharan";
  }
  PrepBytes(String s) {
    name = s;
  }
  public static void main(String[] args) {
    PrepBytes obj = new PrepBytes();
    PrepBytes obj1 = new PrepBytes("Himantica");
    System.out.println(obj.name);
    System.out.println(obj1.name);
  }
}

Output

Hariharan
Himantica

Explanation: In the above approach, we create an object obj using a default no-arg constructor, where the value of the attribute name is set to "Hariharan" by default. Then we create another object obj1 using a parameterized constructor, where it passes the value "Himantica" as an argument to the constructor.

2. Object Creation in Java Using the newInstance() method

We can create an object Class.forName if we know the name of the class and that it has a public default constructor. Class.forName loads the class in Java but does not create any object. To create an object of the class, utilize the new Instance Method of the Class.

Code Implementation:

class PrepBytes {
  public String name;
  PrepBytes() {
    name = "Manoj";
  }

  public static void main(String[] args) {
    try {
      Class pb = Class.forName("PrepBytes");
      PrepBytes s = (PrepBytes) pb.newInstance();
      System.out.println(s.name);
    } catch (Exception e) {
      System.out.println(e);
    }
  }
}

Output

Manoj

Explanation: Class.forName("PrepBytes") loads the class named "PrepBytes" and stores the reference in pb. Then, (PrepBytes) pb.newInstance() creates a new object of the loaded class.

3. Object Creation in Java Using Clone() Method

Whenever we call the clone() method on an object, the JVM creates a new object and copies all of the original object’s content into it. The clone method does not call any constructors when creating an object. To use the clone() method on an object, we must first implement Cloneable and define the clone() method.

Code Implementation:

class PrepBytes implements Cloneable {
    @Override
    protected Object clone()
        throws CloneNotSupportedException
    {
        return super.clone();
    }

    String name = "I am PrepBytes";
    
    public static void main(String[] args)
    {
        PrepBytes obj1 = new PrepBytes();
        try {
            PrepBytes obj2 = (PrepBytes)obj1.clone();
            System.out.println(obj2.name);
        }
        catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
    }
}

Output

I am PrepBytes

Explanation: In the above approach, we are creating a clone object obj2 of an existing object obj1 and not any new object. However, the class needs to first implement the cloneable interface, otherwise, it will throw a CloneNotSupportedException.

4. Object Creation in Java Using newInstance() Method of the Constructor Class

The newInstance() method of the Constructor class is very much similar to the newInstance() method of the Class class, except that we can provide parameters for the different parameterized constructors.

Code Implementation:

import java.lang.reflect.*;

class PrepBytes {
    private String name;
    
    PrepBytes() {}

    public void setName(String name)
    {
        this.name = name;
    }

    public static void main(String[] args)
    {
        try {
            Constructor<PrepBytes> constructor
                = PrepBytes.class.getDeclaredConstructor();

            PrepBytes r = constructor.newInstance();

            r.setName("Hello! Welcome to PrepBytes");
            System.out.println(r.name);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Output

Hello! Welcome to PrepBytes

Explanation: In the above approach, the main method of the class demonstrates the use of the newInstance() method of the Constructor class to create an object of the PrepBytes class dynamically at runtime. It does so by using the getDeclaredConstructor() method of the PrepBytes class to obtain a reference to its default constructor and then calling the newInstance() method of the Constructor class to create a new instance of the class. After creating the object, the code sets the value of its name instance variable using the setName() method and then prints out the value of the name variable to the console.

5. Object Creation in Java Using Deserialization

JVM creates a new object whenever we serialize and then deserialize an object. JVM does not use a constructor to create the object during deserialization. To deserialize an object, we must implement the Serializable interface in the class.

Code Implementation:

import java.io.*;

class PrepBytes implements Serializable {

    private String name;
    PrepBytes(String name)
    {
        this.name = name;
    }

    public static void main(String[] args)
    {
        try {
            PrepBytes d = new PrepBytes("Welcome To PrepBytes!");

            FileOutputStream f
                = new FileOutputStream("file.txt");
            ObjectOutputStream oos
                = new ObjectOutputStream(f);
            oos.writeObject(d);
            oos.close();
            f.close();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Output

Welcome To PrepBytes!

Explanation: In the above approach, the Java code demonstrates how to write an object of the PrepBytes class to a file using serialization. The PrepBytes class implements the Serializable interface, which means that objects of this class can be serialized, or converted to a byte stream that can be stored in a file or transmitted over a network.

The PrepBytes class has a private instance variable called name and a constructor that initializes this variable. The main method of the class creates a new PrepBytes object and writes it to a file called file.txt using the ObjectOutputStream class. This is done by creating a new FileOutputStream to write the serialized data to a file and then wrapping it with an ObjectOutputStream to write the object to the stream. Finally, the output stream and file streams are closed.

Conclusion
In conclusion, there are several ways to object creation in Java. Each method has its own purpose, and developers can choose the most appropriate method based on their specific requirements.

FAQs

Here are some FAQs related to the topic of how to create object in Java:

Q1: What is the most common way of object creation in Java?
Ans: The most common way of object creation in Java is by using the new keyword, followed by the name of the class and the parentheses.

Q2: How to create object in Java using the clone() method?
Ans: To create an object using the clone() method in Java, you need to implement the Cloneable interface and override the clone() method in your class.

Q3: How to create object in Java using the newInstance() method?
Ans: To create an object using the newInstance() method in Java, you need to get a Class object of the class you want to create an instance of, and then call the newInstance() method on it.

Q4: What is the purpose of the Class.forName() method in Java?
Ans: The Class.forName() method in Java is used to dynamically load a class at runtime.

Leave a Reply

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