You can also create an object of a class and access it in another class. This is often used for better organization of classes (one class has all the attributes and methods, while the other class holds the main() method (code to be executed)). Remember that the name of the java file should match the class name.

In Java, there are 5 ways that we can create an object. The object is the basic need in java because in java all this is considered as an object.

  • Using Java new Operator
  • Using Java Class.newInstance() method
  • Using Java newInstance() method of constructor
  • Using Java Object.clone() method
  • Using Java Object Serialization and Deserialization

Table of Content :

This simple way to create an object.

The new operator instantiates a class by allocating memory for a new object and returning a reference to that memory. The new operator also invokes the object constructor.

The instantiation of the class means the same thing as "creating an object." When you create an object, you are creating an "instance" of a class, therefore "instantiating" a class.

Using this ways, we can call any constructor we want to call no argument or parameterized constructors.

Employee employee = new Employee(13827, "John","john@gmail.com","Admin");

package com.javacodestuffs.core.java; import java.io.Serializable; public class Employee implements Serializable { private static final long serialVersionUID = 1L; int id; String name; String email; String dept; Employee() { } public Employee(int id, String name, String email, String dept) { super(); this.id = id; this.name = name; this.email = email; this.dept = dept; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getDept() { return dept; } public void setDept(String dept) { this.dept = dept; } public void getInfo(Employee emp) { System.out.println(emp.toString()); } @Override public String toString() { return "Employee [id=" + id + ", name=" + name + ", email=" + email + ", dept=" + dept + "]"; } }

This class contains a single constructor. You can recognize a constructor because its declaration uses the same name as the class and it has no return type.
package com.javacodestuffs.core.java; public class EmployeeTest1 { public static void main(String[] args) { Employee employee = new Employee(13827, "John", "john@gmail.com", "Admin"); employee.getInfo(employee); } } output: Employee [id=13827, name=John, email=john@gmail.com, dept=Admin]

Java Class.newInstance() method

There are two reflective methods for creating instances of classes:

java.lang.reflect.Constructor.newInstance() and Class.newInstance(). The former is preferred and is thus used in these examples because:

  • Class.newInstance() can only invoke the zero-argument constructor, while Constructor.newInstance() may invoke any constructor, regardless of the number of parameters.
  • Class.newInstance() throws any exception thrown by the constructor, regardless of whether it is checked or unchecked. Constructor.newInstance() always wraps the thrown exception with an InvocationTargetException.
  • Class.newInstance() requires that the constructor be visible; Constructor.newInstance() may invoke private constructors under certain circumstance.

package com.javacodestuffs.core.java; import java.lang.reflect.InvocationTargetException; public class EmployeeTest2 { public static void main(String[] args) throws ClassNotFoundException, InvocationTargetException, NoSuchFieldException { try { Class cls = Class.forName("Employee"); Employee emp = (Employee) cls.newInstance(); emp.setId(1001); emp.setDept("Admin"); emp.setName("John"); emp.setEmail("John@gmail.com"); System.out.println(emp.toString()); } catch (InstantiationException ex) { ex.printStackTrace(); } catch (IllegalAccessException ex) { ex.printStackTrace(); } } }

Java newInstance() method of Constructor class

Syntax

Constructor <Employee> obj =NewInstanceExample1.class.getConstructor(); NewInstanceExample1 obj1 = obj.newInstance()

package com.javacodestuffs.core.java; import java.lang.reflect.Constructor; public class EmployeeTest3 { public static void main(String args[]) { try { Constructor <Employee> obj = Employee.class.getConstructor(); Employee emp = obj.newInstance(); emp.setId(1001); emp.setDept("Admin"); emp.setName("John"); emp.setEmail("John@gmail.com"); System.out.println(emp.toString()); } catch (Exception e) { e.printStackTrace(); } } }

The above 2 ways are called reflective ways of creating objects. Class's newInstances() method internally uses constructors newInstance() method.


clone() method.

Object class had already defined the clone() method. The clone method creates a copy of the existing object.

The clone() method returns the cloned objects.

We need to implement a Clonable interface where we are going to create the objects.

package com.javacodestuffs.core.java; import java.lang.reflect.Constructor; public class EmployeeTest4 extends Employee { private static final long serialVersionUID = 1L; protected Object clone() throws CloneNotSupportedException { return super.clone(); } public static void main(String args[]) { try { Employee employee = new Employee(13827, "John", "john@gmail.com", "Admin"); System.out.println(employee.toString()); EmployeeTest4 emp = (EmployeeTest4) employee.clone(); System.out.println(emp.toString()); } catch (Exception e) { e.printStackTrace(); } } }

Key points when using the clone method.

  • The clonable interface always is implemented.
  • The clone method must be overridden with the other classes.
  • Inside the clone method, we must call super.clone().

Using Object Deserialization

; Object Serialization

Serialization is a process of converting an object into a sequence of bytes. Java ObjectOutputStream class is used to serialize an object.

The writeObject() method of ObjectOutputStream class serialize an object and write the specified object to the ObjectOutputStram class.

Syntax.

public final void writeObject(Object obj) throws IOException

package com.javacodestuffs.core.java; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; public class SerializationExample { public static void main(String[] args) { Employee employee = new Employee(13827, "John", "john@gmail.com", "Admin"); String filename = "employee.ser"; // Serialization process try { FileOutputStream file = new FileOutputStream(filename); // Saving of object in the file ObjectOutputStream out = new ObjectOutputStream(file); out.writeObject(employee); out.close(); file.close(); System.out.println("----------- Before Serialization ----"); System.out.println(employee); System.out.println("Object serialized"); } catch (IOException e) { e.printStackTrace(); } } }

Object Deserialization

When we deserialize any object the JVM internally creates a new Object.

To achieve this we need to implement the Serializable interface.

package com.javacodestuffs.core.java; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; public class DeSerializationExample { public static void main(String[] args) { String filename = "employee.ser"; // DeSerialization process try { FileInputStream file = new FileInputStream(filename); // reading an object from a file ObjectInputStream is = new ObjectInputStream(file); Employee emp = (Employee) is.readObject(); is.close(); file.close(); System.out.println("-----------------Object deserialized-------------- "); System.out.println(emp.toString()); } catch (IOException ex) { System.out.println(ex); } catch (ClassNotFoundException ex) { System.out.println(ex); } } }

Questions/Articles related to 5 Different Ways to Create an Object in Java

Java Object Class and Methods with Examples
Object class in Java

In this article, we have seen 5 Different Ways to Create an Object in Java with examples. We can download the complete code for this article over on GitHub.