Different ways to create an object in Java

This entry is part 15 of 34 in the series Core Java Course

You are required to use “new” operator to create an Object of a Class. This is not true in order to create an Object.

There are several ways to create an Object of a Class :

  • Using new keyword
  • Using new Instance (Reflection)
  • Using Clone
  • Using Deserilization
  • Using ClassLoader
  • … don’t know :)

Now we will explore the different ways to create an Object other than using the new Operator.

Using new Keyword

Using new keyword is the most basic way to create an object. Use new keyword to create and Object of class.

Using New Instance (Reflection)

Have you ever tried to connect to a DB using the JDBC driver in Java? If your answer is yes then you must have seen “Class.forName“. We can also 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 newInstance Method of the Class class.

Note*: If you want to create the Object in this way Class needs to have a public default constructor.

Using Clone

We can also use Clone() Method to create a copy of an existing Object.

 Note*:Below are some additional notes on Clone

  • Here we are creating the clone of an existing Object and not any new Object. 
  • Clone method is declared protected in Object class. So it can be accessed only in subclass or in same package. That is the reason why it has been overridden here in Class.
  • Class need to implement Cloneable Interface otherwise it will throw CloneNotSupportedException.

Using Object Deserialization

Object deserialization can also be used to create an Object. It produces the opposite of serializing an Object.

Using ClassLoader

We can also use Class Loader to create the Object of a Class. This way is much the same as Class.forName option.

 

Series Navigation<< Java Statements tutorial for Beginnersthis keyword in Java >>

15 Comments Different ways to create an object in Java

    1. Deepanshu

      public class Testing {
      public static void main(String[] args) {

      Testing obj = null;
      {

      try {
      obj = (Testing) new Testing().getClass()
      .getClassLoader().loadClass(“Testing”).newInstance();
      // Fully qualified classname should be used.
      } catch (ClassNotFoundException | InstantiationException | IllegalAccessException ex) {
      Logger.getLogger(Testing.class.getName()).log(Level.SEVERE, null, ex);
      }
      System.out.println(obj);
      }
      }
      }

      Reply
  1. aswini chowdary

    hi,
    i have an doubt what is the difference creating the object using class loader and using new instance both same know.please give me some more detailed explanation regarding that.

    thanks in advance..

    Reply
    1. Arun

      @Dev: you need to mention the fully qualified class name like this:

      Class cls = Class.forName(“com.test.JBTClass”);

      Reply
      1. mallikarjunrao

        The fully qualified name of the class is
        Predefined classes are organize in package
        So, before using the class in your program you must give fully qualified name to that class
        Egl
        int double y=Java.util.math.squar(y);
        Here
        Square is method name of class math
        Math is class in until package
        Java is language name or system

        Reply
  2. ms08

    I have code as bellow:

    package com.ex.helloworld;

    public class HelloWorld {

    public static void main(String []args){

    TestLoader obj = null;
    try {
    obj = (TestLoader) new HelloWorld().getClass().getClassLoader().loadClass(“TestLoader”).newInstance();
    } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }

    System.out.println(“TestLoader: “+ obj.toString());

    }

    }

    class TestLoader{

    static int j = 10;

    int i;

    public TestLoader() {

    i = ++j;

    }

    @Override
    public String toString(){
    return “Value Of i: “+ i;
    }

    }

    But when I run , I have a error:

    java.lang.ClassNotFoundException: TestLoader
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at com.ex.helloworld.HelloWorld.main(HelloWorld.java:9)
    Exception in thread “main” java.lang.NullPointerException
    at com.ex.helloworld.HelloWorld.main(HelloWorld.java:16)

    What problem with my code ?

    Reply
    1. unknow

      your program answer 11. your program is correct please check once at “TestLoader” and return “value of i:”+i;( its double quotation )

      Reply
  3. Geek AG

    Is there any difference between :

    Clone :-

    JBTClassClone obj1 = new JBTClassClone();
    JBTClassClone obj2 = (JBTClassClone) obj1.clone();

    And just copying object :-

    JBTClassClone obj = new JBTClassClone();
    JBTClassClone obj1 = obj;

    Reply
    1. J Singh

      There is difference. In first case you are creating clone of object and then assigning while in second you are not creating any clone and assigning the same object to new reference.

      Reply

Leave A Comment

Your email address will not be published. Required fields are marked *