new operator vs newInstance() method in Java

Course Curriculum

new operator vs newInstance() method in Java

new operator vs newInstance() method in Java

In general, new operator is used to create objects, but if we want to decide type of object to be created at runtime, there is no way we can use new operator. In this case, we have to use newInstance() method. Consider an example:

// Java program to demonstrate working of newInstance()

// Sample classes
class A { int a; }
class B { int b; }

public class Test
{
// This method creates an instance of class whose name is
// passed as a string 'c'.
public static void fun(String c) throws InstantiationException,
IllegalAccessException, ClassNotFoundException
{
// Create an object of type 'c'
Object obj = Class.forName(c).newInstance();

// This is to print type of object created
System.out.println("Object created for class:"
+ obj.getClass().getName());
}

// Driver code that calls main()
public static void main(String[] args) throws InstantiationException,
IllegalAccessException, ClassNotFoundException
{
fun("A");
}
}
result:

Object created for class:A
Class.forName() method return class Class object on which we are calling newInstance() method which will return the object of that class which we are passing as command line argument.
If the passed class doesn’t exist then ClassNotFoundException will occur.
InstantionException will occur if the passed class doesn’t contain default constructor as newInstance() method internally calls the default constructor of that particular class.
IllegalAccessException will occur if we don’t have access to the definition of specified class

(Next Lesson) How to start learning Java