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!