Different ways to create an object in Java

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.


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 of the Class 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;
	}
}

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.

/*
 * 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;
	}
}

 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.

/*
 * 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;
	}

}

 

Series Navigation<< Java Statements tutorial for Beginnersthis keyword in Java >>
By | 2017-07-09T12:09:30+00:00 October 28th, 2012|Core Java|15 Comments

About the Author:

15 Comments

  1. nityananda April 8, 2013 at 4:54 am - Reply

    through class loader it is not working.i mean showing exception with null value.

    • Deepanshu February 20, 2016 at 7:37 am - Reply

      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);
      }
      }
      }

      • neel August 2, 2016 at 11:56 am - Reply

        lol

  2. aswini chowdary December 2, 2013 at 12:54 pm - Reply

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

  3. Devnandan Pandey February 17, 2014 at 10:05 am - Reply

    Class.forName() is throwing exception. Its not working

    java.lang.ClassNotFoundException:

    • ms08 September 3, 2015 at 2:29 am - Reply

      Class.forName() in my code also throws java.lang.ClassNotFoundException, I don’t know why

    • Arun September 3, 2015 at 5:42 am - Reply

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

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

    • neel August 2, 2016 at 11:57 am - Reply

      Give the full qualified name of the class

      • mallikarjunrao September 26, 2016 at 3:59 pm - Reply

        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

  4. ms08 September 1, 2015 at 4:05 am - Reply

    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 ?

    • unknow June 20, 2016 at 11:05 am - Reply

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

  5. Geek AG December 19, 2015 at 9:21 pm - Reply

    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;

    • J Singh December 24, 2015 at 3:00 am - Reply

      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.

  6. MNK June 8, 2016 at 11:57 am - Reply

    You need to mention your class file package thats why you are getting not found excepction

  7. suresh November 30, 2016 at 2:11 am - Reply

    very useful.Thanks

Leave A Comment