Table of contents
1.
Introduction
2.
Methods
2.1.
1. Using new keyword
2.2.
2. Using new instance
2.3.
3. Using clone() method
2.4.
4. Using deserialization
2.5.
5. Using newInstance() method of Constructor class
3.
Frequently Asked Questions
3.1.
What is the difference between using the "new" keyword & the "newInstance()" method?
3.2.
When should I use the "clone()" method for object creation?
3.3.
What is the purpose of deserialization in object creation?
4.
Conclusion
Last Updated: Nov 13, 2024
Easy

Object Creation in Java

Author Riya Singh
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In Java, object creation is an important concept that makes the basics of object-oriented programming. Objects are instances of classes that define their properties and behaviors. Creating objects allows you to bring these classes to life within your program, which enables them to interact with each other and perform specific tasks. Java provides many methods for creating objects. The most common approach is using the "new" keyword, which allocates memory for the object and calls its constructor. Another one is the newInstance() method of the Constructor class, which creates objects dynamically. Other methods include the clone() method to create a copy of an existing object and deserialization to recreate objects from serialized data. 

Object Creation in Java

In this article, we will discuss different object creation methods in Java, like using the new keyword, new instance, clone() method, deserialization, and the newInstance() method of the Constructor class. 

Methods

1. Using new keyword

The most common way to create an object in Java is by using the "new" keyword followed by the constructor of the class. The "new" keyword allocates memory for the object & calls the constructor to initialize its state. 

For example:

class Person {
    String name;
    int age;
    Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
}
// Creating an object using the new keyword
Person person1 = new Person("Rahul", 25);


In this example, we define a "Person" class with a constructor that takes a name and age as parameters. We then create a "Person" object named "person1" using the "new" keyword and pass the required arguments to the constructor.

2. Using new instance

Another way to create an object is by using the "newInstance()" method of the Class class. This method creates a new instance of the specified class using its no-argument constructor. 

For example:

class Student {
    String name;
    int rollNumber;
    Student() {
        // Default constructor
    }
}
// Creating an object using newInstance()
try {
    Student student1 = (Student) Class.forName("Student").newInstance();
    student1.name = "Alice";
    student1.rollNumber = 101;
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
    e.printStackTrace();
}


In this example, we define a "Student" class with a default constructor. We use the "Class.forName()" method to get the Class object for "Student" & then call the "newInstance()" method to create a new instance of the "Student" class. We assign values to the object's properties after creation. Note that this method throws checked exceptions, so we must handle them using a try-catch block.

3. Using clone() method

The "clone()" method creates an exact copy of an existing object. It creates a new object with the same state as the original object. To use the "clone()" method, the class must implement the "Cloneable" interface. 

For example:

class Rectangle implements Cloneable {
    int width;
    int height;
    Rectangle(int width, int height) {
        this.width = width;
        this.height = height;
    }
    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}
// Creating an object using clone()
Rectangle rectangle1 = new Rectangle(5, 3);
try {
    Rectangle rectangle2 = (Rectangle) rectangle1.clone();
    System.out.println(rectangle2.width); // Output: 5
    System.out.println(rectangle2.height); // Output: 3
} catch (CloneNotSupportedException e) {
    e.printStackTrace();
}


In this example, we define a "Rectangle" class that implements the "Cloneable" interface. We override the "clone()" method to call the superclass's "clone()" method, which performs a shallow copy of the object. We create a "Rectangle" object named "rectangle1" & then use the "clone()" method to create a new object "rectangle2" with the same state as "rectangle1". The "clone()" method returns an "Object", so we need to cast it to the appropriate type.

4. Using deserialization

Deserialization is the process of recreating an object from its serialized form. Serialization is the process of converting an object into a byte stream that can be stored or transmitted, while deserialization is the reverse process. To use deserialization for object creation, the class must implement the "Serializable" interface. 

For example:

import java.io.*;
class Employee implements Serializable {
    String name;
    int employeeId;
    Employee(String name, int employeeId) {
        this.name = name;
        this.employeeId = employeeId;
    }
}
// Creating an object using deserialization
try {
    // Serialization
    Employee employee1 = new Employee("Bob", 1001);
    FileOutputStream fileOut = new FileOutputStream("employee.ser");
    ObjectOutputStream out = new ObjectOutputStream(fileOut);
    out.writeObject(employee1);
    out.close();
    fileOut.close();
    // Deserialization
    FileInputStream fileIn = new FileInputStream("employee.ser");
    ObjectInputStream in = new ObjectInputStream(fileIn);
    Employee employee2 = (Employee) in.readObject();
    in.close();
    fileIn.close();
    System.out.println(employee2.name); // Output: Bob
    System.out.println(employee2.employeeId); // Output: 1001
} catch (IOException | ClassNotFoundException e) {
    e.printStackTrace();
}

 

In this example, we define an "Employee" class that implements the "Serializable" interface. We create an "Employee" object named "employee1" and serialize it to a file named "employee.ser." We then deserialize the object from the file and create a new "Employee" object named "employee2" with the same state as "employee1." The deserialized object is read using the "readObject()" method of the "ObjectInputStream" class.

5. Using newInstance() method of Constructor class

The "java.lang.reflect.Constructor" class provides the "newInstance()" method, which allows you to create objects dynamically by invoking a constructor. This method is useful when you need to know the class name at compile time or when you want to create objects based on user input. 

For example:

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
class Point {
    int x;
    int y;


    Point(int x, int y) {
        this.x = x;
        this.y = y;
    }
}
// Creating an object using newInstance() method of Constructor class
try {
    Class<?> pointClass = Class.forName("Point");
    Constructor<?> constructor = pointClass.getConstructor(int.class, int.class);
    Point point = (Point) constructor.newInstance(3, 4);
    System.out.println(point.x); // Output: 3
    System.out.println(point.y); // Output: 4
} catch (ClassNotFoundException | NoSuchMethodException | InstantiationException |
         IllegalAccessException | InvocationTargetException e) {
    e.printStackTrace();
}

 

In this example, we define a "Point" class with a constructor that takes two integers as parameters. We use the "Class.forName()" method to get the Class object for "Point" & then obtain the constructor using the "getConstructor()" method, specifying the parameter types. We create a new instance of the "Point" class by invoking the "newInstance()" method on the constructor, passing the required arguments. The "newInstance()" method returns an "Object", so we need to cast it to the appropriate type.

Note: This approach is more dynamic and flexible than the other methods, as it allows you to create objects based on runtime information. However, it requires more code and exception handling, as it involves reflection.

Frequently Asked Questions

What is the difference between using the "new" keyword & the "newInstance()" method?

The "new" keyword is used to create objects directly, while the "newInstance()" method creates objects dynamically using reflection.

When should I use the "clone()" method for object creation?

The "clone()" method is useful when you need to create an exact copy of an existing object, preserving its state.

What is the purpose of deserialization in object creation?

Deserialization allows you to recreate objects from their serialized form, which is useful for storing or transmitting objects.

Conclusion

In this article, we discussed different methods of object creation in Java, such as using the "new" keyword, "newInstance()", "clone()", deserialization, and the "newInstance()" method of the Constructor class. Each approach has its own uses and advantages. Knowing these different techniques is very important for building efficient and maintainable Java programs. 

You can also check out our other blogs on Code360.

Live masterclass