×

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

Graphics Program in Java

Graphics Program in Java The graphics program in Java is part of the Swing program in Java. In this section, we will learn about the implementation of custom graphics using some...

6 minutes read.

DatabaseMetaData in Java

The Data about another data is called Meta data. The DatabaseMetaData interface has the meta data of the database present in the system. It consists of database product name, total...

2 minutes read.

Contextual keywords in Java

Contextual keywords were earlier known as restricted identifiers and restricted keywords. Context keywords are chosen based on their expected placement in the syntactic grammar. These are the keywords in the code...

3 minutes read.

List all files in a Directory in Java

The list of all files in the directory can be done using Java. You should be aware that a directory may include a subfolder and that subdirectory may also contain some...

3 minutes read.

Matrix Multiplication Program in Java

Matrix Multiplication Program in Java The matrix multiplication program in Java is the continuation of the matrix program in Java that we have already discussed earlier. In this section, we will...

3 minutes read.

Generic Linked List in Java

A linear data structure known as a Linked List stores values in nodes. As we already know, each node has two properties: its value and a link to the node...

6 minutes read.

How to Run Applet Program in Java

An applet is a new type of program which is put in a webpage. By inserting applet into a webpage dynamic content can be created. Characteristics of an Applet The applet is...

11 minutes read.

Web Service Response Time Calculation in Java

Administration response time or reaction time is the typical measure of time it takes for a solicitation to be handled by a PC framework, like your organization switch. In the...

4 minutes read.

Java 8 Features

Java 8 Features: After the great success of Java 7, many developers were waiting for the next version of one of the best languages in the tech world. Moreover, on...

6 minutes read.

Why String in Immutable in Java?

Why String in Immutable in Java Immutable means unchangeable or unmodifiable.  Strings in Java are immutable, it means once a string is created, it cannot be modified or changed. Any change...

2 minutes read.

Hello Program in Java

Hello Program in Java The Hello program in Java displays the word Hello on the console. It is the basic program in Java. In this section, we will learn different ways...

3 minutes read.

Java Integer sum() method

The sum() method of Java Integer class add the two specified integers values. It returns the same result as given by + operator. Syntax public static int sum (int a, int b)  Parameters The...

1 minute read.

ArrayList Program in Java

ArrayList Program in Java: In Java, ArrayList is a class that belongs to java.util package. It is the dynamic list that grows or shrinks at run-time as per the requirements....

4 minutes read.

How to resolve Illegal state exceptions in Java

What is IllegalStateException? When a method is called at the incorrect time, a runtime exception called an IllegalStateException is raised in Java. This exception is utilized to show that a method...

3 minutes read.

JRE (Java Runtime Environment)

JRE is an installation package that provides an environment to run the Java program on any Operating System. It does not deal with the development process of any application. It is a part...

2 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 Import Keyword

Java's import keyword used in the code that follows the import statement, a Java class is declared. Once a Java class is declared, it is possible to use the class...

6 minutes read.

Highest precedence in Java

In Java, the operator is the first thing that springs to mind when discussing precedence. The order in which the operators in an expression are evaluated is controlled by a...

3 minutes read.

Java Buffer Reader

When a variable cannot change its value during run time is called a Static way of programming. In this programming, a variable is directly assigned to a value. Program: Import java.io.*; class  A {  ...

4 minutes read.

Java FileOutputStream

What is FileOutputStream?When we need raw stream data written into a file, we need to look for another option: FileOutputStream. It is used when the file's data is byte-oriented. It comes under...

4 minutes read.