How to create an object of a class without using ‘new’ keyword in Java ?


We can create an object of a class without using ‘new’ keyword with the help of the forName() method.

  • forName() is a static method of java.lang.Class package that loads the byte code (.class file) of a class whose name is given as argument.

Example :

class MyClass
{
   public void message()
  {
  System.out.println("ProgrammingPrashn.com");
  }
}
class Main
{
   public static void main(String args[]) throws Exception
  {
   Class c = Class.forName("MyClass"); // [1]
   Object obj = c.newInstance( ); // [2]
   MyClass m = (MyClass) obj; // [3]
   m.message();
  }
}

Explanation :

[1] : forName() method is called, it search and load the .class file of ‘MyClass’. It may throw ClassNotFoundException.

[2] : newInstance()method returns an object of the Object class.

[3] : Explicitly type-cast object obj to MyClass object m.

Output :

ProgrammingPrashn.com