Different ways to create an object in Java

You must be aware of creating an object of a class by using the new keyword, but that is not the only way to create an Object.

There are several other ways to create an object of a class :

  • Using new keyword
  • Using new Instance (Reflection)
  • Using Clone
  • Using Deserialization
  • Using ClassLoader
  • … don’t know 🙂

Using new Keyword

Using a new keyword is the most basic way to create an object. new keyword can be used to create an object of a class.

public class ObjectCreationExample {

	public static void main(String[] args) {
		// Here we are creating Object of JBT using new keyword
		JBT obj = new JBT();
	}
}

class JBT{
	String Owner;
}

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, you have to use the newInstance method of the Class class.

/*
 * Here we will learn to create Object of a class without using new Operator.
 * But newInstance method of Class class.
 */
class CreateObject {
	public static void main(String[] args) {
		try {
			Class cls = Class.forName("JBTClass");
			JBTClass obj = (JBTClass) cls.newInstance();
			JBTClass obj1 = (JBTClass) cls.newInstance();

			System.out.println(obj);
			System.out.println(obj1);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
	}
}

class JBTClass {
	static int j = 10;

	JBTClass() {
		i = j++;
	}

	int i;

	@Override
	public String toString() {
		return "Value of i :" + i;
	}
}

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.

/*
 * Here we will learn to create an Object of a class without using new Operator.
 * For this purpose we will use Clone Interface
 */
class CreateObjectWithClone {

	public static void main(String[] args) {

		JBTClassClone obj1 = new JBTClassClone();
		System.out.println(obj1);
		try {
			JBTClassClone obj2 = (JBTClassClone) obj1.clone();
			System.out.println(obj2);
		} catch (CloneNotSupportedException e) {
			e.printStackTrace();
		}
	}

}

class JBTClassClone implements Cloneable {

	@Override
	protected Object clone() throws CloneNotSupportedException {
		return super.clone();
	}

	int i;
	static int j = 10;

	JBTClassClone() {
		i = j++;
	}

	@Override
	public String toString() {
		return "Value of i :" + i;
	}
}

 Additional notes on Clone

  • Here we are creating the clone of an existing Object and not any new Object. 
  • The clone method is declared protected in Object class. So it can be accessed only in a subclass or in the same package. That is the reason why it has been overridden here in class.
  • A class needs to implement the 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 ClassLoader to create the object of a class. This way is much the same as Class.forName option.

/*
 * Here we will learn to Create an Object using Class Loader
 */
public class CreateObjectWithClassLoader {

	public static void main(String[] args) {

		JBTClassLoader obj = null;
		try {
			obj = (JBTClassLoader) new CreateObjectWithClassLoader().getClass()
					.getClassLoader().loadClass("JBTClassLoader").newInstance();
// Fully qualified classname should be used.
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		System.out.println(obj);
	}
}

class JBTClassLoader {

	static int j = 10;

	JBTClassLoader() {
		i = j++;
	}

	int i;

	@Override
	public String toString() {
		return "Value of i :" + i;
	}

}

19 Comments Different ways to create an object in Java

  1. Krippkrupp

    Java is quite a nice language. It’s annoying that it’s useless to have a language without pointers. Good guide, but throw Java in the trash. A pebble is more useful than Java 🙁

    Reply
  2. 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
  3. 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
    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
  4. 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. 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

Leave A Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.