×

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

  1. Using new keyword
  2. Using a new instance
  3. Using clone() method
  4. Using deserialization
  5. 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.


Related Topics

Java Case Keyword

Case keyword: In this article we are going to learn the concept of a java case keyword.Generally, java case keyword is used with the switch statements.Case keyword is implemented in conditional...

3 minutes read.

Aggregation in Java

Aggregation A "has-a" and "whole/part" connection is the best way to define the aggregate relationship in Java, which exists between two classes. This connection relationship has a higher level of specialisation....

4 minutes read.

Java String hashCode() method

Java String hashCode() method returns hash code for current String. hash code for string object is computed as s[0]*31^(n - 1) + s[1]*31^(n - 2) + ... + s[n - 1] Using int...

2 minutes read.

Java Programming certification

The most common technology utilized in the creation of applications is Java. People and businesses like it because it turns original ideas into useful software solutions. A Java programming certification can...

6 minutes read.

BigDecimal toString() in Java

BigDecimal is a Java class that is a part of the java.math package and the java.base module. It implements the ComparableBigDecimal> interface and extends the Number class. The BigDecimal class...

3 minutes read.

Java FileNotFoundException

FileNotFoundException is another exception class accessible in the java.io bundle. The exemption happens when we attempt to get to that document which isn't accessible in the framework. It is a checked...

5 minutes read.

Difference between final, finally, and finalize()

Difference between final, finally, and finalize() In Java, final, finally and finalize sound similar they are totally different in functionality. Final and finally are the two keywords but the finalize is...

4 minutes read.

Java Constant

A constant is an unchangeable entity in coding, as its title implies. The value which cannot be altered, in other terms. We shall understand about Java constants and exactly how...

3 minutes read.

Different Ways to Print Exception Message in Java

In this section, we will learn how to use various Java Throwable class methods to print exception messages. The Throwable class has the three methods listed below for printing the...

4 minutes read.

Java Protected Keyword

An access modifier is a keyword that Java protects. It can be used to constructors, methods, inner classes, and variables. Variables, methods, and constructors that have been marked protected in...

3 minutes read.

Java Program to Create Set of Pairs Using HashSet

HashSet in Java: HashSet is an assortment in Java that has a place with java.util bundle. It inside utilises HashMap to store components. It is an execution of the Set connection...

11 minutes read.

Applet Life Cycle in Java

In this article, we are going to acknowledge you about what a applet is, what is its life cycle and stages in life cycle, along with the syntax and example...

4 minutes read.

Java Exception Propagation

Java Exception Propagation When an exception is being thrown from the peak of the stack and not getting caught, it runs down the stack to the previous method, which is sitting...

3 minutes read.

Access modifiers in Java

Access modifiers in Java with Example In Java, there are two types of access modifiers one is a non-access modifier, and other is access modifier. If we talk about access modifier, there...

3 minutes read.

Java Obfuscator

Obfuscation is the process of making something unclear or difficult to interpret. Obfuscators are being used in programming to protect the source code from hackers. In this article, we will...

8 minutes read.

Pattern Programs in Java

Pattern Programs in Java In Java, pattern programs are the most important from the perspective of interviews. The pattern programs improve thinking and coding skills. It also helps us to develop a...

27 minutes read.

Binary Strings Without Consecutive Ones in Java

N, an integer, is provided. Our objective is to determine the overall number of strings with length N that do not include successive 1s. Example: Input: 3 Output: 6 Explanation The binary forms of length...

6 minutes read.

Method Overriding in Java

Overriding  Overriding is also known as run time polymorphism, and it is about the same method with the same signatures in different classes. Overriding can be applied only methods. Method Overriding Method Overriding...

8 minutes read.

Alice and Bob Problem Java

Alice and Bob were two friends who liked to play games. Both together found a game, which has the description below. The game begins with an integer num, used to create...

2 minutes read.

URLConnection class in Java

A communication channel between the URL and the program is represented by the Java URLConnection class. It may be utilized to read from and write to the given resource the...

4 minutes read.