×

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

CRC Program in Java

The acronym CRC stands for Cyclic Redundancy Check. It is invented by W. Wesley Peterson in 1961. It is an error detection technique that detects errors in digital networks (also...

5 minutes read.

Java Math pow() Method

The pow() method of Math class returns the value of first argument raised to the power of second argument i.e. ab. Syntax: public static double pow(double a, double b) Parameters: The parameters ‘a’ and...

3 minutes read.

Java.net.SocketException

Exception The problem occurred during the execution of the program. If an exception occurs in the program, the program gets terminated. To skip the exception occurring statements, we have to handle...

4 minutes read.

How to enable java in chrome

The Java module is huge for the Java Runtime Environment (JRE). It permits a program to work with the Java stage to run Java applets. Essentially, each of the undertakings connect...

3 minutes read.

Java Integer floatValue() method

The floatValue() method of Integer class returns a float value for this Integer after a widening primitive conversion. Syntax public float floatValue() Parameters NA Specified by This method is specified by floatValue in class Number Return Value This...

1 minute read.

Java Full Stack

A person who can create both the front end and back end of an application is a full-stack developer. In essence, the term "Java full-stack" refers to a web developer...

9 minutes read.

Hybrid Inheritance in Java

The most crucial OOPs concept in Java is inheritance, which enables the transfer of a class's properties to another class. It describes the Is-A relationship generally. We can create a...

3 minutes read.

URLConnection Class

What is the URL? URL stands for Uniform Resource Locator, is used to specify addresses on the World Wide Web. A URL relates to the identification of any resource connected to the web. URL syntax: Protocol://hostname/other_information(files...

6 minutes read.

Add numbers represented by Linked Lists in Java

For calculating the sum of the two numbers that are represented by a linked list, and then store the result in a new linked list. A linked list's head node...

7 minutes read.

Java vs DotNET

Before understanding the differences between DotNET and Java, one must know about Java and DotNET. Java Java is a general-purpose programming language that is class-based and object-oriented, with minimal implementation dependencies. Regardless of...

9 minutes read.

Java Math asin() Method

The asin() method of Math class computes the trigonometric Arc Sine (inverse of sine ) of an angle. The value returned is between -pi/2 to pi/2. Syntax: public static double asin(double a) Parameters: The...

1 minute read.

Java String join() method

Java String join() method returns a joined String with given delimiter Syntax: public static String join(CharSequence delimeter,charSequence...elements) public static String join(CharSequence delimeter,Iterable<?extens charSequence>elements) Parameters: delimiter: char value to be added with each element elements: char value...

1 minute read.

Java Flags Enum

In a programming language, enumerations represent a group of named constants.For instance; the four suits in a deck of playing cards could be the enumerators Club, Diamond, Heart, and Spade,...

3 minutes read.

Java String trim() method

Java String trim() method returns String after eliminating leading and trailing spaces. Note:- Java String trim() method doesn't trim or omit middle spaces. Syntax: public String trim() Returns: It returns string with omitted leading and...

2 minutes read.

Interface in Java

  Interface in Java In Java, the interface is just like a class that has only static constants and abstract methods. It is used to achieve polymorphism so that it can also...

6 minutes read.

How to create a linked list in Java

Introduction: The linked listing is one type of linear statistics shaped like an array. Not like arrays, linked listing factors aren't stored in a contiguous place. The elements have linked...

3 minutes read.

Gregorian Calendar Java Current Date

GregorianCalendar class uses the Gregorian and Julian calendars. Dates are calculated by projecting present laws forever backward and forward in time. As a consequence, GregorianCalendar may be utilised to create...

8 minutes read.

Reentrant Lock in Java

The Lock interface is implemented by the ReentrantLock class, which also provides methods for synchronising access to shared resources. The code that controls the resource has calls to the lock...

4 minutes read.

How to declare string array in Java

Introduction Array is a data structure with a fixed size, which allows us to store elements of similar type. Data of primitive types like int, char, float, string, etc. can be...

2 minutes read.

Java LinkedHashSet

LinkedHashSet in Java with Example Java LinkedHashSet extends HashSet and Implements the Set interface. It doesn’t contain only duplicate values like HashSet. It also permits the null elements. It maintains the order...

5 minutes read.