×

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

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.

Trimorphic numbers in Java

Wondered what the Trimorphic number is!! In this article, you can learn about what a Trimorphic number is referred to as and how to find whether a number is trimorphic...

3 minutes read.

Java URL Class with Example

Java URL Uniform Resource Locator To find any resource on the internet, you need to have an address of it. The URL and IP addresses are the pointers used for this purpose....

12 minutes read.

What’s New in Java 15

Sealed classes are the new concept that was introduced by Java 15. Sealed classes are a preview feature. Most of the features which are released in java 15 are in...

3 minutes read.

Java String replace() method

Java String replace() method returns new String by replacing old characters with new characters or old CharSequence to new CharSequence. Syntax: public String replace(char oldChar, char newChar) public String replace(CharSequence target, CharSequence replacement) Parameters: oldChar...

2 minutes read.

Short Circuit Logical Operators in Java

When there are two or more relational expressions in a decision-making statement, logical operators are utilized to combine them. The logical operators short circuit and not-short circuit fall into two...

5 minutes read.

Java Return Keyword

The return keyword in Java is used to end a method's execution. the caller receives the return, followed by the appropriate value. The return type of the method, such as...

3 minutes read.

Deadlock in Java

Deadlock is when two or more processes wait for the state to do their tasks, but none of them can do so. It is a very common problem that one...

6 minutes read.

Program to check whether a given character is present in a string or not

In this article, you will understand the logic to find out whether the given character is present in the string or not and find out the position of the specified...

3 minutes read.

Java Math toRadians() Method

The toRadians() method of Java Math class converts an angle measured in degrees to an approximately equivalent angle measured in radian. Syntax: public static double toRadians (double angdeg) Parameters The parameter ‘angdeg’ represents an...

2 minutes read.

Nth node from the end of the Linked list in Java

In talks with leading IT organizations like Google, Amazon, TCS, Accenture, etc., this extremely intriguing subject is constantly brought up. The goal of the problem-solving exercise is to evaluate the...

6 minutes read.

Java Private keyword

A Java access modifier is a private keyword. It can be used to inner classes, methods, and variables. It is the type of access modifier that is most constrained. Privately declared...

4 minutes read.

How to Convert Octal to Decimal in Java

How to Convert Octal to Decimal in Java There are two methods to convert Octal to Decimal: Using parseInt() method Using user-defined logic Using Integer.parseInt() method The Integer.parseInt() method is a static method...

2 minutes read.

Java Strictfp Keyword

Strictfp is used to impose limits on floating-point calculation. It ensures that we will get the same result on every platform while performing an operation with the floating-point variable. The floating-point calculation is platform-dependent due...

1 minute read.

Java Math expm1() Method

The expm1() method of Math class returns ex-1 where e represents Euler’s number. Syntax: public static double expm1(double x) Parameters: The parameter ‘x’ represents the exponent to raise e in the calculation of ex-1. Return...

2 minutes read.

Java Math atan2() Method

The atan2() method of Math class returns an angle theta from the conversion of rectangular coordinates to polar coordinates. Syntax: public static double atan2(double y, double x) Parameters: The parameter ‘y’ represents the ordinate...

3 minutes read.

JDBC Architecture

JDBC: JDBC stands for Java Database Connectivity. Sun Microsystems has a specification called JDBC. JDBC is a Java API (Application Programming Interface) that enables users to interact or communicate with...

4 minutes read.

Java Math negateExact() Method

The negateExact() method of Math class returns the negation for the specified argument, throwing an exception if the result overflows an int or a long. Syntax: public static int negateExact (int a)public...

1 minute read.

Java While Keyword

Depending on a specified Boolean condition, a while loop in Java allows code to be executed repeatedly. The while loop can be viewed as an iterative version of the if...

3 minutes read.

Java ResultSetMetaData

The data about another data is called Metadata. The ResultSetMetaData is used to store the data about ResultSet. The ResultSet Contains the columns, rows, names of table, datatypes etc. these...

2 minutes read.