4 different ways of creating an object in Java

Being a Java developer, almost each one of us must have used the new operator to create objects in our Java programs. But did we ever wonder if we have any other ways to create an object in Java. In this article we will learn about 4 different ways to create an object in Java.


1. Using new keyword

The most common way to create an object in Java is by using the new operator. The code below shows how to create an object using ‘new’ operator.

MyClass clazz = new MyClass();

2. Using Object Cloning

Cloning is the process of creating a copy of an existing object. When we clone an object a new memory location is created and the content of the object is copied to the new location.

The Object class contains a clone() method, which can be used to create clone of an object in Java. The class must however implement the Cloneable interface.

The code below shows how to create a clone of an object:

JavaObject obj1 = new JavaObject();
JavaObject obj2 = obj.clone();

Here we create a new object obj2, by cloning obj1.

To learn more about object cloning refer this article.


3. Using Reflection

Java Reflection is a powerful API which allows inspection of classes, interfaces, methods and fields at runtime. We can also create a new object with the help of reflection. Other than that we can also invoke methods using reflection.

However, in this section we are only concerned about creating an object using reflection. If you have ever written JDBC code you might have come across "Class.forName()". It can be used to create an object in Java.

"Class.forName" itself however doesn’t create an object, it only loads the class into JVM. To create an object we need to use the newInstance() method as shown below:

Class clazz = Class.forName("com.cubearticle.examples.MyClass");
MyClass myClazz = (MyClass)clazz.newInstance();

4. Using Deserialization

Serialization is the process of converting an object into a stream of bytes for the purpose of transmitting it over a network, storing it in a file or database.

Deserialization is the nothing but the reverse of serialization. It is the process of creating an object from its serialized form.

The code below shows how we can create an object using deserialization:

ObjectInputStream inputStream = null;
try {
    inputStream = new ObjectInputStream(new FileInputStream("serialized.txt"));                  
    Employee emp = (Employee)inputStream.readObject(); 
}
catch(ClassNotFoundException e) {
    return null;
}
finally {
    inputStream.close();
}

Here we use ObjectInputStream to read the serialized form of the Employee object stored in "serialized.txt". We use the readObject() method to create the new object (read the content of “serialized.txt” to emp reference variable).

RELATED ARTICLES

2 ways to Create a Thread in Java

Threads in Java can be created in 2 different ways, extending the Thread class and implementing the Runnable interface. This article explains the two ways with suitable examples.

View Article

Using AutoCloseable with 'try-with-resources'

Java 7 added the java.lang.AutoCloseable interface that developers can implement in their custom classes for using them with try-with-resources.

View Article

Chained Exception

Chained exception is a feature introduced with JDK 1.4, which allow developers to associate an exception with another exception.

View Article

Shallow Cloning and Deep Cloning

Cloning an object can happen in two ways Deep and Shallow Cloning. In shallow cloning only object references are copied while in deep copy actual objects are copied to the newly cloned object.

View Article

Exception Handling in Inheritance

There are certain rules that must be followed while throwing exceptions in inheritance and overriding methods. This article discuss about these rules.

View Article

Garbage Collection in Java

Java Garbage Collector is a boon to Java developers; it allows developers to program without worrying about memory management. This article describes the working of Java Garbage Collector in details.

View Article

Understanding static and final in Java

Java provides various modifiers which when used with variables, methods or classes, provides them with special properties. Static and final are are two such modifiers which are used frequently by Ja..

View Article

Understanding Object Cloning

Java provides the clone() method which can be used to create a copy an object. It creates a new memory location and copies the content of the object being cloned into the new location.

View Article

Try-with-resources Statement in Java 7

Java 7 introduces the new 'try-with-resources' statement which help developers to overcome the tedious task of closing the resources that have been used in the program.

View Article

Varargs: Variable Arguments to Methods

Java 5 introduced a new feature called varargs, which allows methods to accept variable number of arguments. They are useful in cases where the number of arguments to be passed to a method is unknown.

View Article