Way2Java

Creating object without new Keyword

Creating an object of a Class without using new Keyword

It is of general practice to create an object with new keyword. It is also possible to create an object without new keyword. This is of logical significance only and not used in regular practice.

public class Hello
{
  public void display()
  {
    System.out.println("Hello World");
  }
  public static void main(String args[]) throws Exception
  {
    Class c1 = Class.forName("Hello");  // throws ClassNotFoundException
    Object obj1 = c1.newInstance( );    // throws InstantiationException and 
			                // IllegalAccessException
    Hello h1 = (Hello) obj1;
    h1.display();
  }
}



Output screenshot of Creating object without new Keyword

Class c1 = Class.forName(“Hello”);
Object obj1 = c1.newInstance( );

forName() is a static method of java.lang.Class that loads the .class file of Hello into the RAM and returns the Hello as an object of class Class. c1 contains the reference of Hello. newInstance() method of class Class returns an object of Object class. Now, obj1 contains the reference of Hello. Internally, JVM may use new keyword.

Hello h1 = (Hello) obj1;

The object obj1 is explicitly type casted to Hello object, h1. It is a long process.

Total there are 5 styles of creating an object in Java without new keyword. This is one. Would you like to know the other 4 styles also.