Different Ways to Create an Object in Java
1. Overview
A Java object is an instance of a Java class. Every object has a state, a behavior, and an identity. Fields (variables) store an object’s state, whereas methods (functions) show the object’s action. Classes serve as blueprints from which objects are instantiated at runtime.
In this tutorial, we’ll learn different ways to create an object in Java.
2. Object Creation in Java
Object creation is mostly a process of allocating memory to hold the data in class fields (also called variables). This process is oftentimes called instantiating a class.
In Java, there are four different ways of creating objects:
a) new keyword
b) newInstance() Method
c) clone() Method
The following sections will explain each of the ways to create an object in depth.
3. Using new Keyword
The new keyword instantiates a class by allocating memory for a new instance of the specified type. It requires one argument, which is a call to a constructor method. Constructor methods are special methods that are supplied by each Java class and are responsible for initializing new objects of that type. The object is created by the new operator and initialized by the constructor.
This is the most common technique to create an object in Java. Often, we will see a Java object created with a statement similar to the one given below:
Date today = new Date();
This expression generates a new Date object (Date is a class inside java.util package). In actuality, this single sentence accomplishes three operations: declaration, instantiation, and initialization. Date today is a variable declaration that informs the compiler that today will refer to an object of type Date. The new operator instantiates the Date class (thus creating a new Date object in memory), and Date() initializes the object.
Consider the example given below:
From the above code, we are creating a Person object using the new keyword:
- Object p1 invokes a non-parameterized constructor, where the value of the variable name is set to “Michael Cole” and UID is set to 101.
- Object p2 invokes a parameterized constructor, where it passes the value “John Bodgan” and 102 to the constructor. Variable name and UID are then assigned these values.
4. Using newInstance() Method
The newInstance() method in Java is used to instantiate an object of the given class dynamically. There are two standard ways of using the newInstance() method:
- newInstance() method of java.lang.Class API
- newInstance() method of java.lang.reflect.Constructor API
4.1. Using newInstance() of Class API
To create an object of a class during runtime, we must call the Class’s newInstance() method, which returns the object of that class. The newInstance() method of java.lang.Class does not consider any parameters or arguments and can be referred to as the no-argument constructor for that class.
Consider the following code for creating a Person class object using the newInstance() method of java.lang.Class:
Class.forName (fully qualified class name) load the class named Person, then newInstance() creates a new object of type Person and returns a reference to it. Now, using the Person reference p, we can make a call to its getters() and setter() and perform some actions.
Please note:
- Both Class.forName() and newIstance() throw exceptions that need to be handled either using try and catch blocks or using the throws keyword.
- The newInstance() method of Class API is deprecated since Java version 9.
4.2. Using newInstance() of Constructor API
The newInstance() method of the Constructor class (java.lang.reflect.Constructor) is analogous to the newInstance() method of the Class class, with the exception that it accepts parameters for parameterized constructors.
Let us demonstrate this approach by creating a Person class object using the newInstance() method of java.lang.reflect.Constructor:
In the above code, first, we need to load the class using Class.forName() method. Next, we’ll call the getConstructor() method to match the data types of parameters to be passed. Finally, in the newInstance() method we pass the required parameter (null in case of no-argument). The newInstance() method will return a new object of PersonTwo class by calling the appropriate constructor.
5. Using clone() Method
The clone() method is a part of the Object class and is used to create a copy of an existing object. It creates an object of a class without invoking any constructor of the class. To clone a method, the corresponding class should have implemented a Cloneable interface which is a marker interface.
In this approach, we will create a Person class object and then clone it into another Person class object.
Note: The cloned object will refer to the same original object through reference p2. However, the cloned object will have a separate memory assignment. This means any changes made in the Person object through reference p2 won’t change the original Person object referred through reference p1. This is because the clone() method makes a shallow copy of the objects.
6. Using Object Deserialization
Object deserialization is a process of extracting an object from a series of byte streams; Serialization does the opposite of that. Its main purpose is to retrieve the saved object from a database/network back into the memory. We need to implement the Serializable interface (marker interface) if we want to serialize or deserialize an object. Consider the example given below:
In this approach, we’re first serializing the Person object p1 into a text file. The writeObject() method will write the object byte stream into a text file. Then using object deserialization, we’re retrieving the Person object back into p2. Similarly, the readObject() method will read the object from the object input stream. Finally, we’ll print the data from the Person object into the console.
7. Conclusion
In this article, we’ve learned different ways for creating an object in Java. First, we have looked into object creation using the new keyword which is the most common way. Then we explored the newInstance() method of Class and Constructor class which is another popular way of creating objects. Next, we utilized the clone() method which creates a shallow copy of an existing object instead of creating a new object. And finally, we’ve used the concept of object serialization and deserialization to create objects in Java.
As always, the code for this article can be found on Github.