×

How Many Ways to Create Objects in Java

Introduction

Java comes under the category of object-oriented programming languages. Since it is object-oriented, everything in Java is considered an object. Java is a diverse programming language that is designed to make computer programmes out of objects that usually interact with each other. Java is also largely considered to be class-based as it works like objects are the instance classes of respective classes.

Object

Object can be defined as a real-world property that has both state and behaviour. Objects accommodate a set of data and code. Data is represented by properties, whereas code, which is sometimes known as methods, is represented by procedures. You need a memory chunk to access any of that data or operations, which is accessed by an object reference variable, also known as the object. Objects are also called containers or memory spaces.

Ways of Creating Objects 

In every Java program, the object needs to be created, otherwise the programme may not execute successfully. So, Java has five ways of creating objects, and they are given below. Each type has different syntaxes and different implementation processes.

 Objects can be created in the following ways:

  • Applying new keyword 
  • Applying clone() method
  • Applying Deserialization method
  • Applying the newInstance() method 
  • Applying the newInstance() method of the Constructor class

1. Applying the new Keyword

It is the simplest method for creating an object. Almost every Java programme is implemented by this new keyword only. When we use the new keyword to create an instance of a class, heap memory is allotted for the newly generated object, and a reference to that object's memory is also returned. The construction of an array also uses the new keyword.

To implement the new keyword, the syntax is as follows:

ClassName   object = new   ClassName(); 

Now let’s see an example Java programme for creating an object.

Code

import java.io.*;
class Demo   
{    
void display()    
{    
System.out.print(" Life is like driving a cycle");    
}    
public static void main(String[] args)   
{    
//creating the object using new keyword 
  
Demo obj1 = new Demo();   


//invoke the display method using the object  
obj1. display();    
}    
}

Output

Life is like driving a cycle

In the above program, we invoked the display method. Not only the method we can also invoke the constructor of the class. New is used for invoking both default and parameterized constructors.

Code

import java.io.*;
public class Demo
{  
//default constructor of the class    
Demo()    
{    
System.out.print(" Life is like driving a cycle");    
}    
public static void main(String[] args)   
{    
//creating an object using new keyword   
Demo obj2 = new Demo();   
}    
}  

Output

Life is like driving a cycle

2. Applying clone() method

This method is used for creating a copy of the existing object and delivering the same copy of the object. It is called the method of Object class. When the clone() method is invoked, the java virtual machine is activated such that a new object is created. All the information in the previously created object will be copied to the new object.

The following syntax is used for creating an object

ClassName newobject = (ClassName)oldobject.clone();

A cloneable interface should be implemented while the clone() method is used. An exception called Clone Not Supported Exception is thrown default by the clone method if the cloneable interface is not supported by the class of the object.

Unlike the new keyword, this clone() method does not support invoking of constructors. If there is no possibility of cloning an instance then, the overridden clone() methods of the subclasses may throw an exception. The syntax as follows

protected Object clone() throws CloneNotSupportedException 

An example program for illustrating clone() method is as follows

Code

import java.io.*;
public class Demo implements Cloneable   
{   
protected Object clone() throws CloneNotSupportedException   
{   
// the clone() method of the super class is called      
return super.clone();   
}   
String str = " A new Object is created ";   
public static void main(String[] args)   
{  
// An object for the Demo class is created    
Demo obj1 = new Demo();   
//try catch block to catch the exception thrown by the method  
try  
{  
//creating a new object of the obj1 suing the clone() method  
Demo obj2 = (Demo) obj1. clone();   
System.out.print(obj2.str);   
}   
catch(CloneNotSupportedException cne)   
{   
cne.printStackTrace();   
}   
}   
}  

Output

A new Object is created

3. Applying the newInstance() method

The other method we have for creating objects in Java is the new instance method. In this method, there are two different syntaxes for creating objects, respectively. One is the Class.forName method.

 If we ever know the class name and if the class is a public default constructor, then we will be able to create an object called Class.forName.

Class. forName doesn't generate any objects; instead, it simply loads the class in Java. You must utilize the new Instance Method of the Class for creating the object for the respective Class.

Let’s see an example Java program to create an object using the new instance method with a Class.forName object.

Code

// A simple Java program to Implement Creation of Object Using new Instance


import java.io.*;
import java.lang.*; 
class Demo
 {
    // Declare and initialize a random string
    String title = " Life is like driving a Cycle";
    public static void main(String[] args)
    {
         try
       {
              Class c = Class.forName("Demo");
             // Creating object of main Demo class using instance method
              Demo o =(Demo)c. newInstance();
            // now print the output
             System.out.print(o.title);
      }
       // Handle the error
        catch(ClassNotFoundException e) 
       {
           e.printStackTrace();
        }
    }
}

Output

Life is like driving a Cycle

The other syntax for creating objects in java is using newInstance() method. It is creating an object for the class “Class”.  this class comes with java. lang package. It produces a fresh instance of the class that this Class object stands for. It gives back the class's most recent instance.

Let’s see an example Java program to create an object using the new instance method with a Class. newInstance() method.

Code

// a simple Java program to Implement Creation of Object Using new Instance
import java.io.*; 
import java.lang.*; 
public class Example  
{  
 // Declare and initialize a random string
String name =" Life is like driving a Cycle";  
public static void main(String args[])  
{  
try {  
//creating object for Example class  
Example o = Example.class.newInstance();   
// print output
System.out.print(o.name);          
}  
// handle the exception
catch(Exception e)  
{  
e.printStackTrace();  
}  
}  
}  

Output

Life is like driving a Cycle

4.  Applying newInstance() method of the Constructor class

This method is similar to the newInstance() method of a Class.  but for a constructor class, there is a new Instance method. this method will be imported from java.lang.reflect.Constructorpackage. Both methods can also be called reflecting types for the creation of objects. The constructor call used to build the new object is returned by the method.

Let’s see an example Java program for constructor class

Code

// Java program to implement newInstance() method of Constructor class
//import the necessary package
import java.lang.reflect.*;
class Demo 
{
private String str;
// Default Constructor of this class Demo
Demo() 
{
}
// Set name of the string
public void setName(String str)
{
// This method refers to present object itself
this.str = str;
}
public static void main(String[] args)
{
// Try block to check for exceptions
try 
{
Constructor<Demo>constructor = Demo.class.getDeclaredConstructor();
Demo d = constructor.newInstance();
// Custom passing
d.setName(" Interview ");
System.out.print (d.str);
}
// Catch block to handle the exceptions
catch(Exception e) 
{
e.printStackTrace();
}
}
}

Output

Interview

5. Applying the Deserialization Method

There are no methods or fields in the Serializable interface. They bring something unique to the class. When we serialize and deserialize an object, the Virtual machine creates a new space. It will not create any object using any constructor.

Serialization

Serialization can be defined as the procedure for conversion of an object into sequence of bytes.ObjectOutputStream is used for serialisation process.

Deserialization

It is the procedure of creating objects from sequence of bytes.

Let’s see an example Java program to create an object using deserialization method

Code

// Java Program for implementing Serialization of an Object
import java.io.*;
class Demo implements Serializable 
{
private String str;
Demo(String str)
{
// This keyword refers to present object itself
this.str = str;
}
public static void main(String[] args)
{
Try
 {
Demo d = new Demo(" Life is like driving a cycle");
             FileOutputStream f1= new FileOutputStream("file.txt");
ObjectOutputStream os = new ObjectOutputStream(f1);
os.writeObject(d);
os.close ();
f.close ();
}
catch (Exception e) 
{
e.printStackTrace ();
}
}
}

Output

Life is like driving a cycle

Related Topics

Java Read File

Java provides its users with many ways of reading a file. To read a text file, you can use a FileReader, BufferedReader, or Scanner. Each utility offers something special for...

6 minutes read.

Java Math ceil() Method

The ceil() method of Math class returns the smallest double value which is closest to negative infinity and is greater than or equal to the argument. Syntax: public static double ceil(double a) Parameters: The...

2 minutes read.

How to check Date is Greater in Java?

In this article, you will be acknowledged about how to check if the given date is greater than the other date or not. We are simply comparing the dates and...

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

Java Instanceof Keyword

To determine whether an object is an instance of the supplied type in Java, use the instanceof operator (class or subclass or interface). The type of comparison in java differentiates the...

4 minutes read.

Java Integer toUnsignedLong() method

The toUnsignedLong() method of Java Integer class returns a long value by simply converting the given argument to long after an unsigned conversion. Syntax public static long toUnsignedLong (int  x) Parameters The parameter ‘x’...

1 minute read.

Display List of TimeZone with GMT and UTC in Java

It is vital to establish the right TimeZone in Java code when working with dates for Daylight Saving Time. In this part, we will present the time zones with GMT. TimeZone Those...

5 minutes read.

Sleeping Barber Problem in Java

The barbershop in this issue has one barber, one barber chair, and N chairs for customers in the waiting area. We may demonstrate the issue by keeping with the original...

6 minutes read.

How to Convert Binary to Decimal in Java

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

2 minutes read.

Example of Static import in Java

Static keyword Java's static keyword is mainly used to control memory. Variables, methods, blocks, and nested classes are compatible with the static keyword. Instead of an instance, the static keyword is...

3 minutes read.

Dutch National Flag Problem in Java

Dutch National Flag (DNF) is a programming issue that Edsger Dijkstra put up. The white, red, and blue hues make up the Dutch flag. The goal is to haphazardly set...

6 minutes read.

Program to Implement FLAMES Game in Java

Friends, Lovers, Affectionate, Marriage, Enemies, and Sibling are all represented by the acronym FLAMES, which also serves as the name of a well-known game. Although, it can be entertaining to...

4 minutes read.

How to download and install Eclipse in Windows?

Download and Install Eclipse on Windows Eclipse is an open source IDE (Integrated Development Environment) which is used to help the programmers to provide a platform to write and run the...

1 minute read.

Java Math round() Method

The round() method of Java Math class returns a long or an int value that is closest to the argument and is rounded to positive infinity. Syntax: public static int round(float a)public...

2 minutes read.

MOOD Factors to Assess a Java Program

In this tutorial, we will comprehendthe meaning of mood factors in Java. For the development of any software system,the quality of anapplication is important. It is more important to maintain large-scale...

4 minutes read.

How to uninstall the Java in Ubuntu

We need java on our computers in our daily lives because there are lots of different applications that are developed using the java environment, so we have to install java...

4 minutes read.

Java Boolean toValue() Method

The valueOf() method of Java Boolean class returns a Boolean object representing the given Boolean or String value. It returns true, if the specified Boolean or string object is true...

2 minutes read.

Difference Between Data Hiding and Abstraction in Java

Abstraction: Data Abstraction and Data Hiding ideas are utilised to show the expected data to the end client and conceal the superfluous subtleties, however, for specific purposes like decreasing the framework's...

10 minutes read.

Java Boolean Class

The Boolean class wraps a value of the Boolean primitive in an object. Its object contains only a single field whose type is Boolean. Boolean Methods: This class contains several different methods...

2 minutes read.

How to Convert String to long in Java

How to Convert String to long in java It is used when you want to perform the mathematical operation on the String which contains long number then the conversion from String...

4 minutes read.