How to Create an Object in Java
How to Create an Object in Java
An object can be defined as a run time entity that contains the blue printof the class. It means that all the member functions and the member variables defined in a class can be accessed using the objects of that class. In other words, we can say that class is a blueprint or template to create objects.
The new keyword is used to create an object. Creating an object of a class is also known as instantiation. An object can be either static, non-static, or final. An object is treated as a variable of a class.
Creating a Class
To create an object and use the methods and functions of the class, we have to create a class first.
Syntax:
class class_name{ //member variables [access_specifier] data_typevariable_name; //member functions [access_specifier] return_typefunction_name(arguments){ //data } }
Creatingan Object
There are six ways to create an object in the Java:
- Usingthe new keyword
- Using theClass.forName()
- Using the clone() method
- Using the newInstance() method of Constructor class
- Using Deserialization
Let’s understand each way one by one:
- Using the new keyword:
It is the most common way to create an object of the class in Java. The new operator instantiates the class and dynamically (at run time) allocates the memory for that object in a heap. The new operator then returns a reference to that memory and that reference is stored in the object we have created.
Syntax:
class_nameobject_name = newclass_name();
Below example shows how to create an object using new keyword:
NewKeywordObject.java
public class NewKeywordObject { //declaring the member variables int a = 10; int b = 20; String str = "hello world"; //defining the member function public void add(){ int c = a+b; System.out.println("Sum is: "+c); } public void displayStr(){ System.out.println("String is: "+str); } public static void main(String args[]) { //creating the object using new keyword NewKeywordObjectobj = newNewKeywordObject(); //calling the class methods using the object created obj.add(); obj.displayStr(); } }
Output:

In the above example, we have created an object of class NewKeywordObjectby using the new keyword. The methods add(), and displayStr() can be accessed using the object obj.
- Using Class.forName() Method
An object of a class can be created using Class.forName() if we know the class name and the class has a public default constructor.
It is a reflective method to create an object.
Itloads the class in Java; however, to create an object of that class, we have to use the newInstance() method.
Syntax:
Class cls = Class.forName(“text”); class_nameobject_name = (class_name) cls.newInstance();
OR
class_nameobject_name = (class_name) Class.forName(“text”).newInstance();
ForNameObject.java
public class ForNameObject{ //declaring the member variables int a = 10; int b = 20; String str = "hello world"; //defining the member function public void add(){ int c = a + b; System.out.println("Sum is: "+c); } public void displayStr(){ System.out.println("String is: "+str); } public static void main(String args[]) { try{ Class cls = Class.forName("ForNameObject"); ForNameObject obj = (ForNameObject) cls.newInstance(); obj.add(); obj.displayStr(); } catch(Exception e){ e.printStackTrace(); } } }
Output:

- Using the clone() Method
The clone() method creates a copy of the already existing object. When the method is called for an object, the JVM creates another object and copies the content of the old object into the new one.
Unlike other objects, the object created using the clone() method doesn’t invoke the constructor of the class.
It should be noted that:
- We need to implement the Cloneable interface of java.lang packagewhile dealing with the clone() method.
- In the clone() method, super.clone() must be called to get the reference of the cloned object.
- The clone() method throws CloneNotSupportedExceptionif the Object class does not support the Cloneable interface. Also, if the subclass overriding the clone() method indicates that the interface cannot be cloned, the same exception is thrown.
Syntax:
protected Object clone() throws CloneNotSupportedException{ return (class_name) super.clone(); } class_nameobject_name = new class_name(); class_namenew_object = (class_name) object_name.clone();
CloneExample.java
public class CloneExample implements Cloneable { @Override protected Object clone() throws CloneNotSupportedException { return (CloneExample) super.clone(); //to create cloned object reference } String name = "This is an example of clone() method"; public static void main(String[] args) { CloneExample obj1 = new CloneExample(); try { CloneExample obj2 = (CloneExample) obj1.clone(); System.out.println(obj2.name); } catch (Exception e) { e.printStackTrace(); } } }
Output:

- Using newInstance() method of Constructor Class
The newInstance() method belongs to the java.lang.reflect.Constructorclass of Java.
Just like the newInstance() method of java.lang.Class class. The newInstance() method of Constructor class is also known for creating an object using reflective ways.
The method returns the new object, which is created after calling the constructor.It can also call the private constructor and parameterized constructor along with the default constructor.
Syntax:
Constructor <class_name>obj_of_constructor =class_name.class.getConstructor(); class_namenew_object_name = obj_of_constructor.newInstance();
Example:
NewInstanceExample.java
import java.lang.reflect.Constructor; public class NewInstanceExample { private String str; public NewInstanceExample(){} public void setString(String str){ this.str = str; } public static void main(String args[]) { try { Constructor <NewInstanceExample> obj =NewInstanceExample.class.getConstructor(); NewInstanceExampleobj_new = obj.newInstance(); obj_new.setString("This is an example of newInstance() method of Constructor class"); //calling the parameterized constructor of the class System.out.println(obj_new.str); } catch(Exception e){ e.printStackTrace(); } } }
Output:

- Using Deserialization
The JVM creates a new class object and allocates a separate space in the memory.In the deserialization method, no constructor is used to create an object.
To deserialize an object, the Serializable interface of the java.io package needs to be implemented. There is no method or field in the Serializable interface.The object deserialization is to create an object from its serialized form.
- Object Serialization:
To serialize an object, the ObjectOutputStream class is used. Serialization is a process to convert an object into a sequence of bytes.
The writeObject() method serializes the object and writes the object to ObjectOutputStream.
Syntax:
public final void writeObject(Object obj) throws IOException
- Object Deserialization:
To deserialize an object, the ObjectInputStream class is used. Deserialization is a process to create an object from the sequence of bytes. The readObject() method reads the object fromObjectOutputStreamanddeserializes it.
Syntax:
public final Object readObject() throws IOException
DeserializationExample.java
import java.io.*; class SerializationExample implements Serializable { public String name; SerializationExample(String name) { this.name = name; } } public class DeserializationExample { public static void main(String[] args) { //serialization try { SerializationExample d = new SerializationExample("example of creating object using object deserialization"); FileOutputStream f = new FileOutputStream("file.txt"); ObjectOutputStreamop_obj = new ObjectOutputStream(f); op_obj.writeObject(d); op_obj.close(); f.close(); System.out.println("Object is serialized"); } catch (Exception e) { e.printStackTrace(); } //deserialization try { SerializationExample d = null; FileInputStream f = new FileInputStream("file.txt"); ObjectInputStreamip_obj = new ObjectInputStream(f); d = (SerializationExample)oos.readObject(); ip_obj.close(); f.close(); System.out.println("Object is deserialized"); System.out.println("String: "+d.name); } catch (Exception e) { e.printStackTrace(); } } }
Output:

In this way, we have learned six different ways to create an object of a class in Java.