Ways to create objects in Java

We all know of the easiest way to create an object in java. It is using the new keyword.

Demo obj = new Demo();

What is the problem with this way of object creation?

Well, the problem is that we have to know the name of the class (here : Demo) while writing code. However, if we wish to manipulate code at runtime, we could use reflection to create new object instances. What does this mean?

import java.lang.reflect.*;

public class CreateObjectUsingReflection{
public static void main(String args[])
{
try {
Class c = Class.forName(args[0]);
Object obj = c.newInstance();
System.out.println("Object created = " + obj);
}
catch (Throwable e) {
System.err.println(e);
}
}
}

As you can see above, we do not need to specify the name of the class while creating an object. We can pass that at runtime as an argument and thus create an object. This is the advantage of using newInstance() over new for creating java objects.

For more information on the different ways to create java objects, please refer to :

For details on using java reflection, please refer to : https://www.oracle.com/technetwork/articles/java/javareflection-1536171.html

I’m a software engineer with a strong interest in algorithms. I love solving puzzles and love the aha moment of arriving at a solution after hours of struggle.

I’m a software engineer with a strong interest in algorithms. I love solving puzzles and love the aha moment of arriving at a solution after hours of struggle.