×

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:

  1. 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:

Create an Object in Java

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:

Create an Object in Java
  • 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:

Create an Object in Java
  • 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:

Create an Object in Java
  • 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:

Create an Object in Java

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


Related Topics

Concurrent Linked Deque in Java with Examples

Introduction Java's concurrent-linked deque, which holds its items as linked nodes, is unconstrained and thread-safe. Concurrent Linked Deque allows for element removal and addition on both sides because it implements the...

4 minutes read.

Java Integer compare() method

The compare() method of Integer class compares the two specified int values. Syntax public static int compare(int x, int y) Parameters The parameters ‘x’ and ‘y’ represent the first and second int values to...

2 minutes read.

Bully Algorithm code in Java

Election algorithms include the bully algorithm, mainly used to select a coordinate. To find a coordinator in a distributed system that can carry out the tasks required by other processes,...

4 minutes read.

Java String getBytes() method

getBytes() method returns sequence of bytes. Syntax: There are three variants of getBytes() method: public byte[] getBytes()        public byte[] getBytes(String charsetName) public byte[] getBytes(Charset charset) Returns: It returns sequence of bytes. Java String getBytes() Example...

2 minutes read.

Caesar Cipher Program in Java

It is among the most popular and straightforward encryption methods. With this method, each letter in the text is swapped out for a letter that is a certain number of...

3 minutes read.

Economical number in Java

Economical number is said to be economically efficient if the number of digits after prime factorization of the original number with their powers is less than the number of digits...

3 minutes read.

Thread Synchronization in Java

In Java, the smallest processing component is a thread, which is a small subprocess. It follows a different course of action. Threads are autonomous. If an exception occurs in one thread,...

6 minutes read.

RMI program in Java

Remote Method Invocation is what it stands for. An object can call the method of another object in a different space address using the RMI API, which may be on the...

3 minutes read.

Java StringBuffer vs StringBuilder

Java StringBuffer vs StringBuilder StringBuffer The StringBuffer class is used to create mutable string. StringBuffer shows writable and growable character sequences. Java StringBuffer program FileName: StringBufferExample.java // A basic program that demonstrates the working...

2 minutes read.

Sparse Numbers in Java

In this section, we will be very well acknowledged about the sparse numbers in Java, how a number can be verified if it is a sparse number or not. Sparse Numbers Any...

3 minutes read.

Finding Odd Occurrence of a Number in Java

In this tutorial, we will learn how to find the odd occurrence of a number through a java program. Let us consider an array of non-negative integers. Here, except for one...

6 minutes read.

Unicode System in Java

In this tutorial, we will understand the meaning and emergence of the Unicode system in java. The Unicode system is one of the important and useful features in the world...

6 minutes read.

Fibodiv Number in Java

Before understanding the concept of the fibodiv number, one should realize what the Fibonacci number is. What are Fibonacci Numbers? The Fibonacci sequence of whole numbers is composed of the numbers 0,...

5 minutes read.

Figurate Number in Java

There have been several uses for figurate or figural numerals throughout history. A number that may be expressed by regular, distinct geometric shapes with spaced evenly points is referred to...

4 minutes read.

How to stop execution after a certain time in Java

We will learn how to stop a long-running execution after a set amount of time in this post. We will take a look at a few alternative approaches to this...

6 minutes read.

Vector in Java

Java Vector Class The Vector class is a legacy class that implements a growable array of objects. The components that it contains can be accessed using an integer index. The size of...

26 minutes read.

Constructor Overloading in Java

In Java, constructors can be overloaded just like methods. The idea of having multiple constructors with various parameter sets so that each function Object()  can carry out a particular task...

3 minutes read.

Tree Implementation in Java

Introduction to Tree A non-linear, hierarchical data structure called a "tree" is made up of a number of nodes, each of which contains a values and a sequence of pointers to...

14 minutes read.

Java Volatile Keyword

The compiler, runtime, or processors may use any kind of optimization if there aren't any required synchronizations. Although most of the time these improvements are advantageous, they occasionally can result...

6 minutes read.

Java callable example

What is callable in Java? Callable is an interface that is present in Java. There are two methods for constructing threads: one is to inherit the Thread class, while the other...

3 minutes read.