×

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 Integer highestOneBit()

The highestOneBit() method of Java Integer class returns an int value with at most a single one-bit, in the position of the highest-order one-bit in the specified int value.  Syntax public static...

1 minute read.

Web Crawler in Java

In this article, you will be acknowledged with what a web crawler in java is and what are its functions. You will also be able to understand where to implement...

4 minutes read.

Hollow Diamond Pattern in Java

Why are patterns important? Programmers frequently create Java pattern programs to practice coding and ace interviews. Interviewers frequently test candidates' logical reasoning and implementation by asking about pattern programs. Hollow Diamond Pattern The...

7 minutes read.

Java Pass-by-Reference

In Java, passing parameters can be done using one of two fundamental methods. Pass-by-value is used for the first and pass-by-reference is used for the second. One thing to keep...

2 minutes read.

Java Boolean Keyword

Boolean keyword In java programming language we basically have two types of primitive data types, Boolean and Numeric (integer and floating-point data types). In this article we are going to learn...

4 minutes read.

Awesome explanation of Strings in Java

What do you mean by String? Strings are a collection of characters that are commonly used in Java programming. Strings are regarded as objects in the Java programming language. “String” is a...

4 minutes read.

Radix Sort in Java

Radix Sort in Java Radix sort in Java uses the digits of the numbers given in the sorted array to sort the numbers. The radix sort uses the place value of...

5 minutes read.

Java Integer parseUnsignedInt() method

The parseUnsignedInt() method of Java Integer class parses the string argument as an unsigned decimal integer. The second parameter parses the string argument as an unsigned integer in the radix specified...

2 minutes read.

Java IO

It is a part of java libraries but is often known as I/O streams, file I/O, and file handling. The Java I/O concept satisfies the need for input processing and...

4 minutes read.

Java LDAP Authentication

WHAT IS LDAP? Clients can communicate with directory services by sending requests and receiving responses using the Lightweight Directory Access Protocol (LDAP). The term "LDAP server" refers to a directory service...

7 minutes read.

How to calculate time complexity of any program in Java

Java : Java's syntax and principles are derived from the C and C++ languages. We know that java is one of the programming language. The main feature of java which is...

3 minutes read.

Java Keywords

Java Keywords The particular words which are used in java programming language that act like a key or important words to write a code are called java keywords. Java Keywords are...

4 minutes read.

Java Applications

The growth in technology is increasing rapidly, so some languages are used for developing them. Java is one such famous programming language which is having numerous applications. The Java Programming...

4 minutes read.

Java Rename File

Renaming a file is the process of changing its name. Using the renameTo() function of the Java File class, renaming operations are possible. A file can be renamed using Java's renameTo()...

3 minutes read.

Objects and Classes in Java

Objects and Classes in Java Classes and objects are the basic concepts of object-oriented programming. It revolves around the real world entity. In Java, the object is a physical and logical...

5 minutes read.

Java Queue

The Java.util package has the interface Queue, which does extend the Collection interface. It is used to protect the parts that are managed using the FIFO approach. Being an interface, the...

5 minutes read.

Java Thread Creation

Java provides the two ways to create a Thread: Implementing the Runnable interface.Extending the Thread class. Implementing Runnable interface The easiest way of creating a thread is to make a class that implements...

5 minutes read.

How to Create an API in Java?

Introduction The API can be abbreviated as Application Programming Interface. An API is a combination of set of classes and interfaces. It is also equivalent to a simple java program. To...

12 minutes read.

Java Integer compareUnsigned() method

The compareUnsigned() method of Integer class compares two int objects numerically by treating the values as unsigned. Syntax public static int compareUnsigned(int x , int y) Parameters The parameters ‘x’ and ‘y’ represent the...

1 minute read.

Least Operator to Express Number in Java

In this article, we will learn about how to obtain a target number using a single number or a single integer by leveraging least operators in Java. There can be...

3 minutes read.