devxlogo

How to Create an Instance of a Class without a New Keyword

How to Create an Instance of a Class without a New Keyword

In the below program, pass any java class name into the method forName of the class java.lang.Class type. Cast it with your java class (in this example “AnyClass”) and get the instance in a reference of AnyClass. Using that reference you can call any method of AnyClass. Thus, you have created a instance without a new keyword.

 public class WithoutNew { public static void main(String s[]) {   try   {    AnyClass c=(AnyClass)Class.forName("AnyClass").newInstance();    c.AnyMethod();   }   catch(Exception e) { System.out.println(e); } }//end of main }//end of class

See also  Professionalism Starts in Your Inbox: Keys to Presenting Your Best Self in Email
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist