×

How many ways to create object in Java?

In this article, you will be acknowledged about the different ways to create an object in java. So far you construct an object from a class, as is common knowledge, because classes serve as the blueprint for objects. However, you will discover numerous, totally unexpected ways of creating in this.

Introduction

As we all know, a class serves as the foundation for objects, and you construct an object from a class. There are various methods for constructing objects of a class in Java. This idea is underappreciated and occasionally shows to be useful because it is disregarded by many engineers and occasionally even comes up in interview questions.

Let's make a list of them and talk about each one individually while using applications to demonstrate how Java's internal workings function when creating objects.

  • Employing new keyword
  • Utilizing new instance
  • the clone() method
  • When deserialization is used
  • Using the newInstance() function of the Constructor class

Let's go over them one at a time and put them into practise by adding a clear java application.

1. New keyword

The simplest method for creating an object in Java is to use the new keyword. The most typical method of creating an object with Java is this one. This is how almost all objects are made. This method allows us to invoke any constructor we desire (no arguments or constructors with parameters).

Let us look at an example program

File name: Gender.java

// Java application to demonstrate object generation using a new keyword
class Gender {


// string declaration and initialization
// each input string
String name = "Male";


public static void main(String[] args)
{
// We will create an object of the class using the new keyword inside main() as is customary //and most common.

Gender m = new Gender();


// Printing and illustrating the item
System.out.println(m.name);
}
}

Output

Male

2. New Instance

If the class has a common default constructor and we are aware of its name, we can generate an object with the Class.forName method. It can be used to construct class objects. Class.forName doesn't actually generate any objects; instead, it simply imports the class in java. You must employ the new instance method of a class to construct an object of the class.

Let us look an example program for the above way

File name: Message.java

// Java application to demonstrate the construction of an object to use a new instance


class Message {


// string declaration and initialization
String name = "Good morning!";
public static void main(String[] args)
{
// Using a try block, look for exceptions
try {


Class cls = Class.forName("GFG");


// Using the instance method, creating a primary class object
GFG obj = (GFG)cls.newInstance();


// Publish and show
System.out.println(obj.name);
}


// To deal exceptions, use a catch block.


// Catch block 1
// managing ClassNotFound Exception
catch (ClassNotFoundException e) {


// The printStacktrace() method can be used to indicate the exception and the line number.
e.printStackTrace();
}
// Managing InstantiationException
catch (InstantiationException e) {


e.printStackTrace();
}
// Managing IllegalAccessException
catch (IllegalAccessException e) {


e.printStackTrace();
}
}
}

Output

Good morning!

3. clone() Method

Copying an object in OOPs refers to making a duplicate of an already existing object. There are numerous techniques to duplicate an object; the copy function Object() { [native code] } and cloning are two of them. In Java, there are two varieties of cloning:

Low-level cloning

cloning in depth

Object cloning includes both deep copy and shallow copy techniques. When we discuss an object, we think of it as a singular entity that cannot be divided further.

Consider the Student object we have. As seen in the following diagram, the Student object is composed of other objects. Personal details objects can be found in the Student object. The Address object is made up of a Street and a city object, and the Name object is made up of FirstName and LastName objects.

The JVM actually produces a new object and replicates all of the content from the preceding object into it whenever clone() is invoked on any object. There is no constructor invoked when an object is created using the clone method. We must implement Cloneable and declare the clone() method in it before we can execute the clone() technique on an object.

Let us look at an example program

File name: Replica.java

// Java program to demonstrate object creation using the clone() method
// Cloneable interface implementation
class Replica implements Cloneable {


protected Object clone()
throws CloneNotSupportedException
{
// Super() keyword refers to parent class
return super.clone();
}


// string declaration and initialization
String name = "Good morning!";
public static void main(String[] args)
{
Replica obj1 = Replica GFG();


// Using a try block, examine for exceptions
try {


// Leveraging the clone() method
Replica obj2 = (Replica)obj1.clone();


// a main class object that was built above, in print and show
System.out.println(obj2.name);
}


// To manage exceptions, use a catch block.
catch (CloneNotSupportedException e) {


// Employing the printStackTrace() method, reveal the exception.
e.printStackTrace();
}
}
}

Output

Good morning!

Note:

In this case, rather than creating any new objects, we are cloning an existing object. Class must implement the Cloneable Interface in order to prevent a CloneNotSupportedException from being thrown.

4. Deserialization

JVM generates a unique object each time we serialise and thereafter deserialize an object. JVM doesn't utilise a constructor to generate the object during deserialization. We must integrate the Serializable interface with in class in order to deserialize an object.

Let us look at an example program to understand it in a better way

File name: Serializablemethod.java

// Serializing an Object using Java Program
// class imports for input and output
import java.io.*;
// putting the Serializable interface into practise
class Serializablemethod implements Serializable {
private String name;
Serializablemethod(String name)
{
// This keyword designates the actual object at hand.
this.name = name;
}
public static void main(String[] args)
{
// Using a try block, look for exceptions
try {
// Generating a class instance in the main() method
Serializablemethod d = new Serializablemethod("Good evening!");


FileOutputStream f
= new FileOutputStream("file.txt");
ObjectOutputStream oos
= new ObjectOutputStream(f);
oos.writeObject(d);
oos.close();


// releasing memory space
f.close();
}


// To manage the exception, use a catch block.
catch (Exception e) {
// Utilizing printStacktrace() method, reveal the exception and the line number.
e.printStackTrace();
}
}
}

Output

Good evening!
Input Object for Deserialization Using the writeObject() method, the example class is serialised and written to the file.txt file.

Let us check for another example program

File name: Serializablemethod1.java

// Java Program Leveraging Deserialization to Demonstrate Object Creation
// class imports for input and output
import java.io.*;
public class Serializablemethod1 {
public static void main(String[] args)
{


// Using a try block, look for exceptions
try {
                            Serializablemethod1  d;


FileInputStream f = new FileInputStream("file.txt");
ObjectInputStream oos = new ObjectInputStream(f);
d = (DeserializationExample)oos.readObject();
}


// To manage exceptions, use a catch block.
catch (Exception e) {


// Apply the printStacjtrace() method to the terminal to display the exception.
e.printStackTrace();
}


System.out.println(d.name);
}
}

Input

For input take a file with any text, for say
Good evening!

Output

Good evening!

5.  Using the newInstance() function of the Constructor class

This is comparable to a class's newInstance() function. The java.lang.reflect.Constructor class contains a single newInstance() method that can be used to build objects. Using the newInstance() method, it is also possible to call the private constructor and the parameterized constructor. Both newInstance() techniques are recognised as reflective approaches to object creation. In actuality, the constructor class's newInstance() method is used internally by the class's newInstance() method.

Let us look at an example program to understand in a better way

File name:

// Object creation using the newInstance() method of the Constructor class is demonstrated //in a Java program.
// importing the necessary classes from the package java.lang
import java.lang.reflect.*;
class Newinstance {
private String name;
Newinstance() {}


            // to change the string's name
public void setName(String name)
{
// This method makes use of the current object directly.
this.name = name;
}
public static void main(String[] args)
{
// Using a try block, look for exceptions
try {
Constructor<Newinstance> constructor = Newinstance.class.getDeclaredConstructor();


Newinstance r = constructor.newInstance();
r.setName("Good Night !");
System.out.println(r.name);
}


// To manage exceptions, use a catch block.
catch (Exception e) {


// Apply the printStackTrace() method to the console to display the exception.
e.printStackTrace();
}
}
}

Output

Good Night!

Related Topics

How to Convert Date to Timestamp in Java

How to Convert Date to Timestamp in Java You can convert Date to Timestamp by using the getTime() method of Date class. It returns the long millisecond from Epoch which can...

1 minute read.

Equilibrium Index of an Array in Java

An array's equilibrium index is the condition where the sum of items with lower and higher indices equals. For example, an array A=[-4,5 2,6,-5] where: a[0]=-4, a[1]=5, a[2]=2, a[3]=6, a[4]=-5 Now according...

4 minutes read.

Session Tracking in Java

When a series of requests from the same User (i.e., requests coming from the same browser) occurs over an extended period of time, servlets employ a mechanism known as session...

3 minutes read.

Java Integer reverseByte() method

The reverseByte() method of Java Integer class returns the value obtained by reversing the order of the bytes in the 2’s complement binary representation. Syntax public static int reverseByte (int i) Parameters The parameter...

1 minute read.

Parallel Arrays Sort in Java

Sorting is a technique of arranging a sequence of numbers in ascending order, that is, the first number being lowest and gradually incrementing the numbers such that the last number...

7 minutes read.

Char and String differences in Java

Characters in Java Character (char) belongs to the characters group, which represents symbols in a character set, such as alphabets and numerals. A Java char has 16 bits in length and has a range...

5 minutes read.

Java Socket Programming

Java Socket Programming Socket programming is used for the communication between the applications, i.e., client and server running on different JRE may be connection-oriented or connectionless. The client program can be designed using the...

8 minutes read.

Java Integer compare() method

The compare() method of Integer class compares the two specified int values. Syntax public static int compare(int x, int y) Parameters The parameters ‘x’ and ‘y’ represent the first and second int values to...

2 minutes read.

Java Float Keyword

Float: In general, there are two categories of data types: primitive data types and non-primitive data types. So, float is the data type which is a primitive data type. Declarating the variables and...

3 minutes read.

Java Set to List

In this article, you will be acknowledged about how the process of conversion from Set or HashSet to LinkedList happens and what are the possible ways involved in conversion process. First...

4 minutes read.

How to increment and decrement date using Java?

Before understanding how to increment and decrement the date, one must know about the Calendar class in Java. The Java calendar class offers methods for converting dates between a given moment...

3 minutes read.

Java Maven Silicon

Maven is a build automation tool that is mostly used for Java applications. It allows you to manage the build, reporting, and documentation of a project from the central location. Maven provides...

4 minutes read.

Hollow Diamond Pattern in Java

Why are patterns important? Programmers frequently create Java pattern programs to practice coding and ace interviews. Interviewers frequently test candidates' logical reasoning and implementation by asking about pattern programs. Hollow Diamond Pattern The...

7 minutes read.

Difference between Abstract Class and Interface

There is a similarity between abstract class and interface is that we cannot create objects for both of them. But irrespective of this, there are some differences between them, let’s...

2 minutes read.

Java Thread Dump Analyzer

Thread: A thread is a PC program that is stacked into the PC's memory and is under execution. It tends to be executed by a processor or a bunch of processors....

15 minutes read.

Java Program to Print Permutations of String

A string is given and you need to print all the possible ways for that string. Permutation is arranging the characters of a string to get outputs from the given...

3 minutes read.

Java Math tan() Method

The tan() method of Java Math class returns the trigonometric tangent of the specified angle. Syntax: public static double tan(double a) Parameters: The parameter ‘a’ represents an angle measured in radians. Return Value: The tan() method...

2 minutes read.

Print Matrix Diagonally in Java

The aim is to print the elements of a matrix of size n*n in some kind of a diagonal pattern. Input : mat[3][3] = {{1, 2, 3},                      {4, 5, 6},                      {7,...

3 minutes read.

How to download Eclipse for Java

Introduction: We write a java program, and when we want to run it, we need software to run it. Eclipse is a kind of software used to execute a JavaFX...

3 minutes read.

How to Change the Day in the Date using Java?

To operate with the date and time in Java, we need the Calendar abstract class. It provides a number of helpful interfaces that enable us to convert dates between a...

4 minutes read.