How Many Ways to Create Objects in Java
Introduction
Java comes under the category of object-oriented programming languages. Since it is object-oriented, everything in Java is considered an object. Java is a diverse programming language that is designed to make computer programmes out of objects that usually interact with each other. Java is also largely considered to be class-based as it works like objects are the instance classes of respective classes.
Object
Object can be defined as a real-world property that has both state and behaviour. Objects accommodate a set of data and code. Data is represented by properties, whereas code, which is sometimes known as methods, is represented by procedures. You need a memory chunk to access any of that data or operations, which is accessed by an object reference variable, also known as the object. Objects are also called containers or memory spaces.
Ways of Creating Objects
In every Java program, the object needs to be created, otherwise the programme may not execute successfully. So, Java has five ways of creating objects, and they are given below. Each type has different syntaxes and different implementation processes.
Objects can be created in the following ways:
- Applying new keyword
- Applying clone() method
- Applying Deserialization method
- Applying the newInstance() method
- Applying the newInstance() method of the Constructor class
1. Applying the new Keyword
It is the simplest method for creating an object. Almost every Java programme is implemented by this new keyword only. When we use the new keyword to create an instance of a class, heap memory is allotted for the newly generated object, and a reference to that object's memory is also returned. The construction of an array also uses the new keyword.
To implement the new keyword, the syntax is as follows:
ClassName object = new ClassName();
Now let’s see an example Java programme for creating an object.
Code
import java.io.*;
class Demo
{
void display()
{
System.out.print(" Life is like driving a cycle");
}
public static void main(String[] args)
{
//creating the object using new keyword
Demo obj1 = new Demo();
//invoke the display method using the object
obj1. display();
}
}
Output
Life is like driving a cycle
In the above program, we invoked the display method. Not only the method we can also invoke the constructor of the class. New is used for invoking both default and parameterized constructors.
Code
import java.io.*;
public class Demo
{
//default constructor of the class
Demo()
{
System.out.print(" Life is like driving a cycle");
}
public static void main(String[] args)
{
//creating an object using new keyword
Demo obj2 = new Demo();
}
}
Output
Life is like driving a cycle
2. Applying clone() method
This method is used for creating a copy of the existing object and delivering the same copy of the object. It is called the method of Object class. When the clone() method is invoked, the java virtual machine is activated such that a new object is created. All the information in the previously created object will be copied to the new object.
The following syntax is used for creating an object
ClassName newobject = (ClassName)oldobject.clone();
A cloneable interface should be implemented while the clone() method is used. An exception called Clone Not Supported Exception is thrown default by the clone method if the cloneable interface is not supported by the class of the object.
Unlike the new keyword, this clone() method does not support invoking of constructors. If there is no possibility of cloning an instance then, the overridden clone() methods of the subclasses may throw an exception. The syntax as follows
protected Object clone() throws CloneNotSupportedException
An example program for illustrating clone() method is as follows
Code
import java.io.*;
public class Demo implements Cloneable
{
protected Object clone() throws CloneNotSupportedException
{
// the clone() method of the super class is called
return super.clone();
}
String str = " A new Object is created ";
public static void main(String[] args)
{
// An object for the Demo class is created
Demo obj1 = new Demo();
//try catch block to catch the exception thrown by the method
try
{
//creating a new object of the obj1 suing the clone() method
Demo obj2 = (Demo) obj1. clone();
System.out.print(obj2.str);
}
catch(CloneNotSupportedException cne)
{
cne.printStackTrace();
}
}
}
Output
A new Object is created
3. Applying the newInstance() method
The other method we have for creating objects in Java is the new instance method. In this method, there are two different syntaxes for creating objects, respectively. One is the Class.forName method.
If we ever know the class name and if the class is a public default constructor, then we will be able to create an object called Class.forName.
Class. forName doesn't generate any objects; instead, it simply loads the class in Java. You must utilize the new Instance Method of the Class for creating the object for the respective Class.
Let’s see an example Java program to create an object using the new instance method with a Class.forName object.
Code
// A simple Java program to Implement Creation of Object Using new Instance
import java.io.*;
import java.lang.*;
class Demo
{
// Declare and initialize a random string
String title = " Life is like driving a Cycle";
public static void main(String[] args)
{
try
{
Class c = Class.forName("Demo");
// Creating object of main Demo class using instance method
Demo o =(Demo)c. newInstance();
// now print the output
System.out.print(o.title);
}
// Handle the error
catch(ClassNotFoundException e)
{
e.printStackTrace();
}
}
}
Output
Life is like driving a Cycle
The other syntax for creating objects in java is using newInstance() method. It is creating an object for the class “Class”. this class comes with java. lang package. It produces a fresh instance of the class that this Class object stands for. It gives back the class's most recent instance.
Let’s see an example Java program to create an object using the new instance method with a Class. newInstance() method.
Code
// a simple Java program to Implement Creation of Object Using new Instance
import java.io.*;
import java.lang.*;
public class Example
{
// Declare and initialize a random string
String name =" Life is like driving a Cycle";
public static void main(String args[])
{
try {
//creating object for Example class
Example o = Example.class.newInstance();
// print output
System.out.print(o.name);
}
// handle the exception
catch(Exception e)
{
e.printStackTrace();
}
}
}
Output
Life is like driving a Cycle
4. Applying newInstance() method of the Constructor class
This method is similar to the newInstance() method of a Class. but for a constructor class, there is a new Instance method. this method will be imported from java.lang.reflect.Constructorpackage. Both methods can also be called reflecting types for the creation of objects. The constructor call used to build the new object is returned by the method.
Let’s see an example Java program for constructor class
Code
// Java program to implement newInstance() method of Constructor class
//import the necessary package
import java.lang.reflect.*;
class Demo
{
private String str;
// Default Constructor of this class Demo
Demo()
{
}
// Set name of the string
public void setName(String str)
{
// This method refers to present object itself
this.str = str;
}
public static void main(String[] args)
{
// Try block to check for exceptions
try
{
Constructor<Demo>constructor = Demo.class.getDeclaredConstructor();
Demo d = constructor.newInstance();
// Custom passing
d.setName(" Interview ");
System.out.print (d.str);
}
// Catch block to handle the exceptions
catch(Exception e)
{
e.printStackTrace();
}
}
}
Output
Interview
5. Applying the Deserialization Method
There are no methods or fields in the Serializable interface. They bring something unique to the class. When we serialize and deserialize an object, the Virtual machine creates a new space. It will not create any object using any constructor.
Serialization
Serialization can be defined as the procedure for conversion of an object into sequence of bytes.ObjectOutputStream is used for serialisation process.
Deserialization
It is the procedure of creating objects from sequence of bytes.
Let’s see an example Java program to create an object using deserialization method
Code
// Java Program for implementing Serialization of an Object
import java.io.*;
class Demo implements Serializable
{
private String str;
Demo(String str)
{
// This keyword refers to present object itself
this.str = str;
}
public static void main(String[] args)
{
Try
{
Demo d = new Demo(" Life is like driving a cycle");
FileOutputStream f1= new FileOutputStream("file.txt");
ObjectOutputStream os = new ObjectOutputStream(f1);
os.writeObject(d);
os.close ();
f.close ();
}
catch (Exception e)
{
e.printStackTrace ();
}
}
}
Output
Life is like driving a cycle