How to Create Object in Java

In Java, objects serve as fundamental entities in object-oriented programming. They are essential for executing programs, and in this section, we will explore different methods of object creation in Java.

Java offers five approaches to creating objects:

  • Using new Keyword
  • Using clone() method
  • Using the newInstance() method of the Class class
  • Using the newInstance() method of the Constructor class
  • Using Deserialization

Using new Keyword:

The most commonly used approach for creating objects or instances of a class in Java is by using the new keyword. When we create an object using the new keyword, it allocates memory on the heap for the newly created object and returns a reference to that allocated memory.

The new keyword is also utilized to create arrays in Java. It allows us to allocate memory for multiple elements of the same type, providing a convenient way to work with collections of objects or primitives.

The syntax for creating an object using the new keyword is as follows:

ClassName object = new ClassName();

CreateObjectExample1.java

public class CreateObjectExample   
{    
void show()    
{    
System.out.println("Welcome to javaTpoint");    
}    
public static void main(String[] args)   
{    
//creating an object using new keyword   
CreateObjectExample obj = new CreateObjectExample();   
//invoking method using the object  
obj.show();    
}    
}

Output:

Welcome to javaTpoint

CreateObjectExample2.java

public class CreateObjectExample1 
{  
//constructor of the class    
CreateObjectExample2()    
{    
System.out.println("Welcome to javaTpoint");    
}    
public static void main(String[] args)   
{    
//creating an object using new keyword   
CreateObjectExample1 obj = new CreateObjectExample1();   
}    
}

Output:

Welcome to javaTpoint

Using clone() Method:

The clone() method is a member of the Object class in Java. It allows creating a copy of an object and returning that copy. When the clone() method is invoked, the JVM creates a new object and copies the contents of the original object into the newly created object. It’s important to note that the clone() method does not invoke any constructors.

To use the clone() method, the class of the object must implement the Cloneable interface. This interface serves as a marker, indicating that the object’s class supports cloning. If the object’s class does not implement Cloneable, invoking the clone() method will result in a CloneNotSupportedException being thrown.

Subclasses that override the clone() method can also throw an exception if cloning is not supported for a specific instance.

Syntax:

protected Object clone() throws CloneNotSupportedException

The syntax for creating a new object:

ClassName newobject = (ClassName) oldobject.clone();

CreateObjectExample3.java

public class CreateObjectExample2 implements Cloneable   
{   
@Override  
protected Object clone() throws CloneNotSupportedException   
{   
//invokes the clone() method of the super class      
return super.clone();   
}   
String str = "New Object Created";   
public static void main(String[] args)   
{  
//creating an object of the class     
CreateObjectExample2 obj1 = new CreateObjectExample2();   
//try catch block to catch the exception thrown by the method  
try  
{  
//creating a new object of the obj1 suing the clone() method  
CreateObjectExample2 obj2 = (CreateObjectExample2) obj1.clone();   
System.out.println(obj2.str);   
}   
catch (CloneNotSupportedException e)   
{   
e.printStackTrace();   
}   
}   
}

Output:

New Object Created	

Using newInstance() Method:

Another way to create an object in Java is by using the newInstance() method of the Class class. This method dynamically creates an object by invoking the default constructor of the class. It returns a new instance of the class represented by the object.

The newInstance() method internally utilizes the newInstance() method of the Constructor class to instantiate the object. It is important to note that the default constructor (a constructor with no arguments) must be present in the class for this approach to work.

Syntax:

public T newInstance() throws InstantiationException, IllegalAccessException

The newInstance() method of the Class class may throw three exceptions: IllegalAccessException, InstantiationException, and ExceptionInInitializerError.

We can create an object in the following ways:

ClassName object = ClassName.class.newInstance();

Or

ClassName object = (ClassName) Class.forName("fully qualified name of the class").newInstance();

In the provided statement, the forName() method is a static method belonging to the Class class. It accepts a String parameter, className, which represents the fully qualified name of a class. The forName() method returns the Class object associated with the specified class name. It is responsible for loading the class into the JVM’s memory but does not create an object of that class. If the class cannot be found or loaded, the forName() method throws a ClassNotFoundException. In case the linkage of the class fails, a LinkageError may be thrown.

To create an object, we utilize the newInstance() method of the Class class. This method can only be used if we know the name of the class and the class has a public default constructor. The newInstance() method dynamically creates an instance of the class by invoking the public default constructor. It returns a reference to the newly created object.

The following example demonstrates the usage of the newInstance() method to create a new object:

CreateObjectExample4.java

public class CreateObjectExample3 
{   
void show()    
{    
System.out.println("A new object created.");    
}    
public static void main(String[] args)   
{   
try  
{  
//creating an instance of Class class  
Class cls = Class.forName("CreateObjectExample3");   
//creates an instance of the class using the newInstance() method  
CreateObjectExample3 obj = (CreateObjectExample3) cls.newInstance();   
//invoking the show() method  
obj.show();   
}   
catch (ClassNotFoundException e)   
{   
e.printStackTrace();   
}   
catch (InstantiationException e)   
{   
e.printStackTrace();   
}   
catch (IllegalAccessException e)   
{   
e.printStackTrace();   
}   
}   
}

Output:

A new object created.

Using newInstance() Method of Constructor class:

The newInstance() method of the Constructor class is an alternative approach to creating objects in Java. It is part of the java.lang.reflect package and provides a reflective way of object creation. This method allows us to invoke both parameterized and private constructors.

Compared to the newInstance() method of the Class class, the newInstance() method of the Constructor class offers more flexibility and control over object creation. It enables us to create objects using constructors that require arguments or constructors that are not accessible through regular means.

Syntax:

public T newInstance(Object... initargs) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException

The method of the Constructor class takes an array of Objects as its argument. If the constructor requires primitive types as parameters, the values of those types should be wrapped in the appropriate wrapper Objects. It gives IllegalAccessException, IllegalArgumentException, InstantiationException, InvocationTargetException, and ExceptionInInitializerError Exceptions.

We can create an object in the following way:

Constructor<Employee> constructor = Employee.class.getConstructor();   
Employee emp3 = constructor.newInstance();

Let’s create a program that creates an object using the newInstance() method.

CreateObjectExample5.java

import java.lang.reflect.*;   
public class CreateObjectExample4  
{   
private String str;   
CreateObjectExample5()   
{   
}   
public void setName(String str)   
{   
this.str = str;   
}   
public static void main(String[] args)   
{   
try  
{   
Constructor<CreateObjectExample4> constructor = CreateObjectExample4.class.getDeclaredConstructor();   
CreateObjectExample4 r = constructor.newInstance();   
r.setName("JavaTpoint");   
System.out.println(r.str);   
}   
catch (Exception e)   
{   
e.printStackTrace();   
}   
}   
}

Output:

JavaTpoint

Using Deserialization:

Serialization in Java refers to the process of converting an object into a sequence of bytes, allowing it to be stored in a file, sent over a network, or saved in persistent storage. Conversely, deserialization involves the reconstruction of an object from its serialized form, converting the byte stream back into an object.

When we serialize or deserialize an object in Java, the JVM creates a new object without invoking the constructor. Instead, it uses the serialized data to recreate the object’s state.

To enable deserialization, the class of the object being serialized must implement the Serializable interface. The Serializable interface acts as a marker interface, indicating that the class can be serialized and deserialized. It does not contain any methods to implement.

Serialization: The writeObject() method of ObjectOutputStream class in Java is utilized to serialize an object and send it to the output stream.

Syntax:

public final void writeObject(object x) throws IOException

Deserialization: The readObject() method of ObjectInputStream class in Java is used for deserializing an object and retrieving objects from a stream.

Syntax:

public final Object readObject() throws IOException,ClassNotFoundException

Employee.java

import java.io.Serializable;    
public class Employee implements Serializable  
{    
int empid;    
String empname;    
public Empoyee(int empid, String empname)   
{    
this.empid = empid;    
this.empname = empname;    
}    
}

Serialization of Java Object:

In the program, an object of the Employee class is serialized using the writeObject() method of ObjectOutputStream class, and its state is stored in the “employee.txt” file.

SerializationExample.java

import java.io.*;    
class SerializationExample   
{    
public static void main(String args[])  
{    
Try  
{    
//Creating the object    
Employee emp = new Employee(198054,"Andrew");    
//Creates a stream and writes the object    
FileOutputStream fout=new FileOutputStream("employee.txt");    
ObjectOutputStream out=new ObjectOutputStream(employeeout);    
out.writeObject(emp);    
out.flush();    
//closes the output stream    
out.close();    
System.out.println("Successfully Created");    
}  
catch(Exception e)  
{  
System.out.println(e);  
}    
}    
}

Output:

Successfully Created

Deserialization of Java Object:

DeserializationExample.java

import java.io.*;    
class DeserializationExample   
{    
public static void main(String args[])  
{    
try  
{    
//Creating a stream to read the object    
ObjectInputStream in=new ObjectInputStream(new FileInputStream("employee.txt"));    
Employee e=(Employee)in.readObject();    
//prints the data of the serialized object    
System.out.println(e.empid+" "+e.empname);    
//closing the input stream    
in.close();    
}  
catch(Exception e)  
{  
System.out.println(e);  
}    
}    
}    

Output:

198054 Andrew

Among the five methods mentioned above, the new keyword and both newInstance() methods utilize the constructor for object creation, whereas the remaining two methods do not rely on the constructor.

To gain further insights on creating objects in Java, make sure to visit tutorials.freshersnow.com.