How Many Ways to Create an Object in Java?
As you know, a class is a blueprint for an object, and you can create objects from it. There are several ways to create objects of classes in Java. This concept is so underrated that many programmers ignore it and sometimes even perceptively ask about it, so it sometimes proves useful.
Method:
There are several ways to create objects in Java. Let's list and describe them and see programmatically how Java objects are created internally
- Using new keyword
- Using a new instance
- Using clone() method
- Using deserialization
- Using newInstance() method of Constructor class
Method 1: Using the new keyword
The most fundamental method for creating an object in Java is to use the new keyword.In Java, this is the most common method for creating objects.This method is used to create nearly all objects.We can use this technique to call any constructor we want (no parameterized or argument constructors).
// Java program to Illustrate Creation of Object
class LC {
// Declaring and initializing string
// Custom input string
String name = "JavaTPoint";
// Main driver method
public static void main(String[] args) {
// As usual and most generic used we will
// be creating object of class inside main()
// using new keyword
LCobj = new LC();
// Print and display the object
System.out.println(obj.name); } }
Output:
JavaTPoint
Method 2:
If you know the name of the class, you can use the new instance to create an object named Class.forName. It has a public default constructor. It can be used to create objects of the class. Class.forName loads the class in Java but does not create the object. You should use the new class instance method to create an object of the class.
// Java program to Illustrate the Creation of an Object
// Using a new Instance
// Main class
class LC {
// Declaring and initializing string
String name = " JavaTPoint ";
// Main driver method
public static void main(String[] args)
{
// Try block to check for exceptions
Class cls = Class.forName("LC");
// Creating object of main class
// using instance method
LC obj = (LC)cls.newInstance();
// Print and display
System.out.println(obj.name) ; }
// Catch block to handle the exceptions
// Catch block 1
// Handling ClassNotFound Exception
catch (ClassNotFoundException e) {
// Display the exception along with the line number
// using printStacktrace() method
e.printStackTrace(); }
// Catch block 2
// Handling InstantiationException
catch (InstantiationException e) {
e.printStackTrace();
}
// Catch block 2
// Handling IllegalAccessException
catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
Output:
JavaTPoint
Method 3: Using the clone() Method
When clone() is called on an object, the Java Virtual Machine (JVM) creates a new object and copies allthe contents of the previous object into it. . The constructor is not called when you create an object using the Clone method. It must implement Cloneable and define a to be used with an object Clone() method.
// Java program to Illustrate Creation of Object
// Using clone() method
// Implementing Cloneable interface
class LCimplements Cloneable {
// Method 1
@Override
protected Object clone()
throws CloneNotSupportedException {
// Super() keyword refers to parent class
return super.clone(); }
// Declaring and initializing string
String name = "JavaTPoint";
// main driver method
public static void main(String[] args) {
LC obj1 = new LC();
// Try block to check for exceptions
try {
// Using the clone() method
LC obj2 = (LC)obj1.clone();
// Print and display the main class object
// as created above
System.out.println(obj2.name); }
// Catch block to handle the exceptions
catch (CloneNotSupportedException e) {
// Display the exception
// using printStackTrace() method
e.printStackTrace(); } } }
Output:
JavaTPoint
Method 4: Utilizing deserialization
JVM makes a different item when we serialize and deserialize an item. In deserialization, JVM utilizes no constructor to make the article. To deserialize an article, we want to carry out the Serializable connection point in the class.
// Java Program Illustrate Serializing an Object
// Importing input-output classes
import java.io.*;
// Main class
// Implementing the Serializable interface
class LC implements Serializable {
// Member variables
private String name;
GFG(String name)
{
// This keyword refers to the current object itself
.name = name;
}
// Main driver method
public static void main(String[] args)
{
// Try block to check for exceptions
try {
// Creating object of class in main() method
LC d = new GFG("JavaTPoint");
FileOutputStream f= new FileOutputStream("file.txt");
ObjectOutputStreamoos= new ObjectOutputStream(f);
oos.writeObject(d);
oos.close();
// Freeing up memory resources
f.close();
}
// Catch block to handle the exceptiona
catch (Exception e) {
// Display the exception along with line number
// using printStacktrace() method
e.printStackTrace(); } } }
Output:
JavaTpoint
// Java Program for Creation of Object
// Deserialization use
// input output classesImporting
import java.io.*;
// Main class
public class LC {
// Main driver method
public static void main(String[] args)
{
// Try block to check for exceptions
try {
LC d;
// Creating FileInputStream class object
FileInputStream f= new FileInputStream("file.txt");
// Creating ObjectInputStream class object
ObjectInputStreamoos= new ObjectInputStream(f);
d = (DeserializationExample)oos.readObject();
}
// Catch block to handle the exceptions
catch (Exception e) {
// Display the exception on console
// using printStacjtrace() method
e.printStackTrace();
}
System.out.println(d.name);
}
}
Output:
JavaTPoint
Method 5: Use the newInstance() method of the constructor class
The java.lang. Reflect class contains onlyone new instance () method. You can create an object using a constructor class. You can also use the newInstance() method tocallprivateandparameterized constructors. Both reflective methods for object creation are new instance () methods. The newInstance() method of the constructor class is used internally by the newInstance() method.
// Java Program for Creation of Object
// using newInstance() method of Constructor class
// Importing required classes from the java.lang package
import java.lang.reflect.*;
// Main class
class LC {
// Member variables of this class
private String name;
// Constructor of this class
LC() {}
// Method 1
// To set the name ofthe string
public void setName(String name)
{
// This method refers to the current object itself
this.name = name;
}
// Main driver method
public static void main(String[] args)
{
// Try blocking check for exceptions
try {
Constructor<LC> constructor= LC.class.getDeclaredConstructor();
LC r = constructor.newInstance();
// Custom passing
r.setName("JavaTPoint");
System.out.println(r.name);
}
// Catch block to handle the exceptions
catch (Exception e) {
// Display the exception on the console
// using printStackTrace() method
e.printStackTrace();
}
}
}
Output:
JavaTPoint
There are many ways to copy objects. Copy constructors and cloning are two of them.
Java has two types of cloning:
Both shallow and deep copies are types of object duplication.
- Deep Cloning When we talk about objects, we think of them assingle entities that cannot be broken down further.
Suppose we have a Student object. The Student object contains other objects, as shown in the following illustration. The name and address objects are in the Student object Address objects consist of streets and cities, and Name objects contain FirstName and LastName objects. When we talk about students, we refer to the entire object network.
- Shallow Cloning Whenever you use the default implementation of Java's clone() method, you use shallow cloning.
The main object is copied when an object is flat-cloned, but the smaller objects are not.The original object and its copy shares an inner object.
The lack of independence between two objects is a drawback of shallow copies. When a student's name object changes, so do the other student objects.
The following example shows a Student object and a reference variable, MBA. Next, clone MBA and create a second Student object. The MBA will move with the mca whenever you change its Address object and try to moveOut(). This is because the Address object is the same in her MBA and mca objects. If one address changes, both objects change.
Deep Cloning is a copy of an object that is completely independent.
Therefore, we must ensure that each member class implements the Cloneable interface and overrides the Object class's clone() method for the deep copy.
The other Student object remains unchanged when the Address object of one Student object is modified. The following code demonstrates that we are employing a copy constructor on the Student object and the inner objects. We need to keep copying all of the Student object's nested elements until there are only primitive types and immutable left to make a deep clone.
Name and number are the two instance variables of the Street object. The number is not an object but rather a primitive integer value. It is not transferable. An independent copy is automatically created when we create a second instance variable. The string is an object that cannot be changed after it has been created, as shown in the preceding code. As a result, we can share it without making a full copy.