Ways to Create Objects in Java

We already knew that Java is an object-oriented programming language. This has led to the development of many applications for desktop, mobile, and other gadgets. In other words, java is nothing without an object. Therefore, knowing to create an object is a must for a java developer to beware of.

This article will guide you regarding all the possible ways of creating an object in Java.

What is an object?

The general definition for an object is that it is a real-world entity with some characteristics and behavior. In other words, it is a physical and logical entity.

An example of an object in real life is a bike. The various characteristics of a bike are the color, brand name, model, etc. Whereas, the attributes include mileage, brake system, speed, and so on.
In the same way, objects are also available in the Java programming language. Here, the objects consist of properties and methods/functions.

Characteristics of an object:

The objects contain three main characteristics:

  • State: The state of an object represents the value in it.
  • Behavior: The behavior represents the object’s functionality.
  • Identity: It is denoted by a unique ID. The Java Virtual Machine(JVM) makes use of this to identify an object. The user cannot have this identity.

Ways to Create Objects in Java:

In Java, a programmer can use five possible ways to create an object:

  • Using the new Keyword
  • Using the newInstance() method of the Class
  • By using the newInstance() method of the Constructor class
  • Using Object Serialization and Deserialization method
  • Using the clone() method

1) Using the new Keyword:

The new Keyword or the operator is used to create an object in Java. This is the most used and the simplest method of all to achieve it. It is usually followed by call constructors with parameters or no arguments.

Syntax to create an object using new keyword in java:

Class_name object_name = new class_name();

Example program to create an object using new Keyword:

public class FirstCode {
String a = "Learn with FirstCode";

public static void main(String args[]){
FirstCode f = new FirstCode(); // creation of object f
System.out.println(f.s);
}
}

Output:

Learn with FirstCode

2) Using the newInstance() method of the Class

The next technique used to create an object using java is the newInstance() method. It belongs to the java.lang package. Here, the newInstance() method calls the constructor with no arguments. When the name of the Class is known, the Class.forName constructor is used to lead the Class.

Syntax for creating an object using NewInstance method of Class:

public T newInstance() throws InstantiationException, IllegalAccessException

InstantiationException: It is returned if the class or method is inaccessible.
IllegalAccessException: It is returned if the class does not have a no-argument constructor. Even in cases where the Class represents an interface, an abstract class, a primitive, or an array, this exception is thrown.

Sample program for creating an object using NewInstance method of Class:

public class FirstCode{
String s = "Learn with FirstCode";
public static void main(String args[])
{
try
FirstCode f = FirstCode.class.newInstance(); // f is the object created
System.out.println(f.s);
}
catch(Exception e)
{
e.printStackTrace();
}}}

Output:

Learn with FirstCode

3) Using Java newInstance() method of the Constructor class

We can use the newInstance() function in this method too. The only difference is that this time, the constructor has parameters. It is available in the java.lang.reflect.Constructor class to create objects.

Syntax for using the newInstance() method of Constructor class to create an object:

public T newInstance(Objects initargs)

The exceptions that it throws are:

IllegalAccessException: If the constructor class cannot be accessed, this exception is thrown.
IllegalArgumentException: Thrown when the number of actual and formal parameters differ.
InstantiationException: Invoked if the constructor denotes an abstract class.
InvocationTargetException: Invoked when an underlying constructor throws an exception.
ExceptionInInitializerError: Thrown if the initialization done by this method fails.

Sample program for using the newInstance() method of Constructor class to create an object:

import java.lang.reflect.Constructor;
public class FirstCode{
String s = "Learn with FirstCode";
public static void main(String args[])
{
try {
Constructor f = FirstCode.class.getConstructor();
NewInstanceFirstCode f1 = f.newInstance();
System.out.println(f1.s);
}
catch(Exception e)
{
e.printStackTrace();
}
}
}

Output:

Learn with FirstCode

4) Using Java Object Serialization and Deserialization method

The next method to create an object is by implementing the Sizeable interface of the java.io package. This is possible due to the presence of the Java Virtual Machine. The JVM creates a space when serialization or deserialization of an object is done.

This method needs no constructor to achieve it. We can use the Sizeable interface in Java for serializing and deserializing the objects.

Object serialization in Java:

In the object serialization method, an object is converted into an order of bytes. We use the ObjectOutputStream Class to achieve it and the method that is used is the writeObject() method with parameters.

Syntax for creating an object using serialization method:

public final void writeObject(Object obj) throws IOException

Object Deserialization in Java:

In the above method, we have created an order or sequence of bytes. Here, we tend to reframe the sequence of bytes and create an object. The ObjectInputStream class contains the readObject() method that is used for deserialization. This method does not contain any parameters.

Syntax for creating an object using deserialization method:

public final Object readObject() throws IOException

ClassNotFoundException: If the serialized Class is not found.
InvalidClassException: If there is a fault with the serialization that took place.
IOException: If the input or output is in the wrong format, this exception is thrown.
OptionalDataException: If the presence of primitive data is encountered instead of objects, this error is thrown.

Sample program for creating object using serialization and deserialization method:

import java.io.*;
class FirstCode implements Serializable {
public int a;
public String s;
public FirstCode(int a, String s)
{
this.i = i;
this.s = s;
}
}
public class DeserializationFirstCode
{
public static void main(String args[])
{
FirstCode object = new FirstCode(1, "Learn with FirstCode")
String filename = "FirstCode.ser" // the name of the file should have an extension .ser

//Serialization starts
try
{
FileOutputStream file = new FileOutputStream(filename); // Saving the Object in the file
ObjectOutputStream out = new ObjectOutputStream(file);
out.writeObject(object); // Serializing the object
out.close(); // Closing the ObjectOutputStream method
close.file();
System.out.println("Serialization Done");
}
catch(IOException e)
{
eprintStackTrace();
}
FirstCode obj = null;

// Deserialization starts
try
{
FileInputStream file = new FileInputStream(filename);
ObjectInputStream ois = new ObjectInputStream(file);
obj = (FirstCode)ois.readObject();
ois.close();
file.close();
System.out.println("Deserialization Done");
System.out.println("The integer value is: " +obj.a);
System.out.println("The given String is: " +obj.s);
}
catch(IOException e)
{
System.out.println("IOException is encountered");
}
catch(ClassNotFoundException e)
{
System.out.println("ClassNotFoundException is Encountered");
}
}
}

Output:

Serialization Done
Deserialization Done
The integer value is: 1
The given String is: Learn with FirstCode

5) Using Java clone() method

All these methods discussed above are used to create new objects. In comparison, the clone() method is used to create a new object and copy the content to it. No constructor is involved when an object is created using the clone() method.

The Class Cloneable is implemented to use the clone() method. The Cloneable interface is present in the java.lang package. To attain the cloned object reference, the super.clone() method is called by the Class.

Syntax to create an object using the clone() method:

protected Object clone() throws CloneNotSupportedException

CloneNoSupportedException: When the Cloneable interface is not supported by the object class, this exception is thrown.

Example program to create an object using the clone() method:

public class FirstCode implements Cloneable
{
protected Object clone() thrown CloneNotSupportedException
{
return super.clone();
}
String s = "Learn with FirstCode";
public static void main(String args[])
{
CloneObject o = new CloneObject();
try
{
CloneObject o2 = (CloneObject) o.clone();
System.out.println(o.s);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}

Output:

Learn with FirstCode

Conclusion:

Now, you might have a clear view of how many methods an object can be created in Java. If you ask me for a good suggestion, I will pick the first method (Using the new Keyword) method to create an object.
You can also try the other four methods as each has its own unique characteristics and serves various purposes. Thank you for reading our article. Have a happy learning.

Leave a Reply

Your email address will not be published. Required fields are marked *