×

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

Java ArrayList

Java ArrayList Class A Java ArrayList class is a dynamic array which is used to store the elements. It is a part of collection framework. It implements the List Interface and inherits the...

12 minutes read.

Tetranacci Number in Java

This article mainly describes tetranacci number identification and the Java Program for Tetranacci numbers. Tetranacci number Tetranacci numbers and Fibonacci numbers are related. The key contrast is that a Tetranacci number depends...

3 minutes read.

Java Try Keyword

The try block in Java is used to run essential code, such as connection closure, among other things. Whether an exception is resolved or not, the Java try block has...

3 minutes read.

Java Variable

The variable is the basic unit of storage in a program. We define a variable using an identifier, a type, and an optional initializer in Java. In Java, variables must be...

4 minutes read.

How to set path in Java

To make programs that can run on our systems, we need to install programming language-related software in our systems. Different programming languages require different types of software, aka IDEs (Integrated Development...

5 minutes read.

How to Convert Object to String in Java

How to Convert Object to String in Java You can convert any Object to String in Java whether it is a user-defined class, StringBuilder or StringBuffer, etc. There are two methods...

2 minutes read.

Reserved Keywords in Java

In Java, a reserved term is used as a code key called a keyword. Because they are predefined, these terms cannot be used for anything else. They cannot serve as...

3 minutes read.

Ternary Operator in Java

In some cases, the if...else expression in Java can be replaced by a ternary operator. Visit the Java if...else statement first before learning about the ternary operator. Ternary operator in Java A...

3 minutes read.

Majority Element in Java

It's an extremely intriguing question that is commonly asked in job interviews at prestigious IT firms like The Google, Amazon, TCS, and The Accenture, etc. By figuring out the solution, one may...

10 minutes read.

Java vs JavaScript

Java Vs JavaScript Java and JavaScript, both play an important role in the field of Computer Technology. Most people think JavaScript is a part of Java. But it is not entirely...

4 minutes read.

Difference between next() and nextline() in Java

One of the simplest methods for receiving input of the basic data types, also including int, double, and strings, in Java, is to use the Scanner class, which is part...

3 minutes read.

Internal Working of ArrayList in Java

Java's version of a resizable array is called ArrayList. The dynamic growth of an array list ensures that there is always room for new elements. ArrayList's backing data structure is...

8 minutes read.

Thread Program in Java

Thread Program in Java Thread program in Java is the continuation of multithreading program in Java. In this topic, we will learn about the usage of threads, race condition in multithreading,...

8 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.

Java Trim

Leading and leaving spaces are removed by the built-in Java String trim() method. Space seems to have the Unicode element of "x0040." Java trim() function looks for all of these...

3 minutes read.

Arithmetic exception in Java

Exception Handling is one of the most potent ways of handling runtime faults and preserving the application's normal flow. In Java, an exception is an out-of-the-ordinary state, and exceptions are...

3 minutes read.

Java Speech Recognition

The customer experience and convenience are improved with its utilization. Command and control interest in buying and voice synthesizers are supported by the cross-platform API defined by the API. For...

4 minutes read.

Java Read File Line by line

Java provides two options to read files line by line. Each option offers different benefits and has its own set of drawbacks. Following are the ways through which on accomplish...

5 minutes read.

Java Integer hashCode() method

The hashCode()  method of Java Integer class returns a hash code for this Integer.  Syntax public int hashCode() public static int hashCode(int value)  Parameters The parameter ‘value’ represents a value whose hash code...

1 minute read.

Segment Tree in Java

Binary trees can address a variety of issues; however, the Segment Tree is more efficient in terms of time complexity. The segment tree in Java is represented using an array. Native...

4 minutes read.