The Wayback Machine - https://web.archive.org/web/20240621035510/https://www.geeksforgeeks.org/different-ways-create-objects-java/
Open In App

Different ways to create objects in Java

Last Updated : 14 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

There are several ways by which we can create objects of a class in java as we all know a class provides the blueprint for objects, you create an object from a class. This concept is under-rated and sometimes proves to be beneficial as this concept is bypassed by many programmers and sometimes even do ask from interview perceptive.

Methods: 

There are many different ways to create objects in Java. Let us list them later discussing later taking individually with the help of programs to illustrate internal working by which we can create objects in Java.

  1. Using new keyword
  2. Using new instance
  3. Using clone() method
  4. Using deserialization
  5. Using newInstance() method of Constructor class

Let us discuss them one by one and implement the same by appending a clean java program for the same.

Method 1: Using new keyword

Using the new keyword in java is the most basic way to create an object. This is the most common way to create an object in java. Almost 99% of objects are created in this way. By using this method we can call any constructor we want to call (no argument or parameterized constructors).

Example

Java




// Java program to Illustrate Creation of Object
// Using new keyword
  
// Main class
class GFG {
  
    // Declaring and initializing string
    // Custom input string
    String name = "GeeksForGeeks";
  
    // Main driver method
    public static void main(String[] args)
    {
        // As usual and most generic used we will
        // be creating object of class inside main()
        // using new keyword
        GFG obj = new GFG();
  
        // Print and display the object
        System.out.println(obj.name);
    }
}


Output

GeeksForGeeks

Method 2: Using new instance

If we know the name of the class & if it has a public default constructor we can create an object Class.forName. We can use it to create the Object of a Class. Class.forName actually loads the Class in Java but doesn’t create any Object. To create an Object of the Class you have to use the new Instance Method of the Class.

Example

Java




// Java program to Illustrate Creation of Object
// Using new Instance
  
// Main class
class GFG {
  
    // Declaring and initializing string
    String name = "GeeksForGeeks";
  
    // Main driver method
    public static void main(String[] args)
    {
        // Try block to check for exceptions
        try {
  
            Class cls = Class.forName("GFG");
  
            // Creating object of main class
            // using instance method
            GFG obj = (GFG)cls.newInstance();
  
            // Print and display
            System.out.println(obj.name);
        }
  
        // Catch block to handle the exceptions
  
        // Catch block 1
        // Handling ClassNotFound Exception
        catch (ClassNotFoundException e) {
  
            // Display the exception along with line number
            // using printStacktrace() method
            e.printStackTrace();
        }
  
        // Catch block 2
        // Handling InstantiationException
        catch (InstantiationException e) {
  
            e.printStackTrace();
        }
  
        // Catch block 2
        // Handling IllegalAccessException
        catch (IllegalAccessException e) {
  
            e.printStackTrace();
        }
    }
}


Output: 

GeeksForGeeks

Method 3:  Using clone() method

Whenever clone() is called on any object, the JVM actually creates a new object and copies all content of the previous object into it. Creating an object using the clone method does not invoke any constructor. In order to use the clone() method on an object we need to implement Cloneable and define the clone() method in it.

Example

Java




// Java program to Illustrate Creation of Object
// Using clone() method
  
// Main class
// Implementing Cloneable interface
class GFG implements Cloneable {
  
    // Method 1
    @Override
    protected Object clone()
        throws CloneNotSupportedException
    {
        // Super() keyword refers to parent class
        return super.clone();
    }
  
    // Declaring and initializing string
    String name = "GeeksForGeeks";
  
    // Method 2
    // main driver method
    public static void main(String[] args)
    {
        GFG obj1 = new GFG();
  
        // Try block to check for exceptions
        try {
  
            // Using the clone() method
            GFG obj2 = (GFG)obj1.clone();
  
            // Print and display the main class object
            // as created above
            System.out.println(obj2.name);
        }
  
        // Catch block to handle the exceptions
        catch (CloneNotSupportedException e) {
  
            // Display the exception
            // using printStackTrace() method
            e.printStackTrace();
        }
    }
}


Output

GeeksForGeeks

Note:  

  • Here we are creating the clone of an existing Object and not any new Object.
  • Class need to implement Cloneable Interface otherwise it will throw CloneNotSupportedException.

Method 4: Using deserialization

Whenever we serialize and then deserialize an object, JVM creates a separate object. In deserialization, JVM doesn’t use any constructor to create the object. To deserialize an object we need to implement the Serializable interface in the class.

Example 1

Java




// Java Program Illustrate Serializing an Object
  
// Importing input output classes
import java.io.*;
  
// Main class
// Implementing the Serializable interface 
class GFG implements Serializable {
  
    // Member variables
    private String name;
    GFG(String name)
    {
        // This keyword refers to current object itself
        this.name = name;
    }
  
    // Main driver method
    public static void main(String[] args)
    {
        // Try block to check for exceptions
        try {
            // Creating object of class in main() method
            GFG d = new GFG("GeeksForGeeks");
  
            FileOutputStream f
                = new FileOutputStream("file.txt");
            ObjectOutputStream oos
                = new ObjectOutputStream(f);
            oos.writeObject(d);
            oos.close();
  
            // Freeing up memory resources
            f.close();
        }
  
        // Catch block to handle the exceptiona
        catch (Exception e) {
            // Display the exception along with line number
            // using printStacktrace() method
            e.printStackTrace();
        }
    }
}


Output: 

GeeksForGeeks

Object of DeserializationExample class is serialized using writeObject() method and written to file.txt file.

Example 2

Java




// Java Program Illustrate Creation of Object
// Using Deserialization
  
// Importing input output classes
import java.io.*;
  
// Main class
public class GFG {
  
    // Main driver method
    public static void main(String[] args)
    {
  
        // Try block to check for exceptions
        try {
  
            GFG d;
  
            // Creating FileInputStream class object
            FileInputStream f
                = new FileInputStream("file.txt");
  
            // Creating ObjectInputStream class object
            ObjectInputStream oos
                = new ObjectInputStream(f);
            d = (DeserializationExample)oos.readObject();
        }
  
        // Catch block to handle the exceptions
        catch (Exception e) {
  
            // Display the exception on console
            // using printStacjtrace() method
            e.printStackTrace();
        }
  
        System.out.println(d.name);
    }
}


Output: 

GeeksForGeeks

Method 5: Using newInstance() method of the constructor class

This is similar to the newInstance() method of a class. There is one newInstance() method in the java.lang.reflect.Constructor class which we can use to create objects. It can also call the parameterized constructor, and private constructor by using this newInstance() method. Both newInstance() methods are known as reflective ways to create objects. In fact newInstance() method of Class internally uses newInstance() method of Constructor class. 

Example

Java




// Java program to illustrate creation of Object
// using newInstance() method of Constructor class
  
// Importing required classes from java.lang package
import java.lang.reflect.*;
  
// Main class
class GFG {
  
    // Member variables of this class
    private String name;
  
    // Constructor of this class
    GFG() {}
  
    // Method 1
    // To set name ofthe string
    public void setName(String name)
    {
        // This method refers to current object itself
        this.name = name;
    }
  
    // Main driver method
    public static void main(String[] args)
    {
        // Try block to check for exceptions
        try {
            Constructor<GFG> constructor
                = GFG.class.getDeclaredConstructor();
  
            GFG r = constructor.newInstance();
  
            // Custom passing
            r.setName("GeeksForGeeks");
            System.out.println(r.name);
        }
  
        // Catch block to handle the exceptions
        catch (Exception e) {
  
            // Display the exception on console
            // using printStackTrace() method
            e.printStackTrace();
        }
    }
}


Output: 

GeeksForGeeks



Previous Article
Next Article

Similar Reads

Different Ways to Convert java.util.Date to java.time.LocalDate in Java
Prior to Java 8 for handling time and dates we had Date, Calendar, TimeStamp (java.util) but there were several performance issues as well as some methods and classes were deprecated, so Java 8 introduced some new concepts Date and Time APIs' (also known as Joda time APIs') present in java.time package. Java 7: Date, Calendar, TimeStamp present ins
3 min read
How to Create Different Packages For Different Classes in Java?
Let us first know what is a class and package in Java. Class in java is a model for creating objects. It means that the properties and actions of the objects are written in class. Properties are represented by variables and actions of the objects are represented by methods. So, a class contains variables and methods. The same variables are also ava
6 min read
Different Ways to Create the Instances of Wrapper Classes in Java
Wrapper Class a class whose object wraps or contains primitive data types. When we create an object to a wrapper class, it contains a field and in this field, we can store primitive data types. In other words, we can wrap a primitive value into a wrapper class object. Methods: We can use two ways to construct the instance of the Wrapper Classes Usi
5 min read
Get Two Different Objects Into a TreeSet in Java
In Java, TreeSet is a part of the Java Collection Framework and is located in the java.util package. It implements the NavigableSet interface and extends the AbstractSet and TreeSet is known for maintaining its elements in sorted order, either based on their natural order. This must be consistent with equals if it is to correctly implement the Set
3 min read
How to Create a Spring Bean in 3 Different Ways?
Spring is one of the most popular Java EE frameworks. It is an open-source lightweight framework that allows Java EE 7 developers to build simple, reliable, and scalable enterprise applications. This framework mainly focuses on providing various ways to help you manage your business objects. It made the development of Web applications much easier t
5 min read
How to Create Array of Objects in Java?
Prerequisite - Different ways to create objects in Java Java programming language is all about classes and objects as it is an object-oriented programming language. When we require a single object to store in our program we do it with a variable of type Object. But when we deal with numerous objects, then it is preferred to use an Array of Objects.
6 min read
How to Create TreeMap Objects using Comparable Interface in Java?
In Java, the TreeMap class is an implementation of the SortedMap interface that stores key-value pairs in a sorted order based on the natural ordering of the keys. By default, the keys are sorted in ascending order. If you want to sort the keys based on a custom ordering criteria, you can use the Comparable interface to define the natural ordering
6 min read
Different Ways to Copy Content From One File to Another File in Java
In Java, we can copy the contents of one file to another file. This can be done by the FileInputStream and FileOutputStream classes. FileInputStream Class It is a byte input stream class which helps in reading the bytes from a file. It provides different methods to read the data from a file. FileInputStream fin = new FileInputStream(filename); This
3 min read
Different ways for String to Integer Conversions in Java
Given a String in Java, the task is to convert this String into Integer. Examples: Input: str = "1234" Output: 1234 Input: str = "456" Output: 456 Convert using Integer.parseInt(String) The Integer class has a static method that returns an integer object representing the specified String parameter. Syntax : public static int parseInt(String str) th
2 min read
Different Ways to Print First K Characters of the String in Java
Given a string str and a positive integer k, the task is to write a Java program to print the first k characters of the string. If the length of the string is less than k then print the string as it is. Examples: Input: str = "GeeksForGeeks", k = 5 Output: Geeks Explanation: The first k characters of the given string is 'Geeks'. Input: str = "Geeks
3 min read
Article Tags :
Practice Tags :