new operator vs newInstance() method

Total Post:113

Java  Class 
 260  View(s)
Rate this:

new operator vs newInstance() method in Java ?

  1. Post:140

    Re: new operator vs newInstance() method

    new operator vs newInstance() method in Java:

    new operator is used to create objects but when you wants to create that in runtime thats no way you can use new operator. you have to use newInstance() method in this case.  

    // Java program to demonstrate working of newInstance() 

    class A {  int a; }
    class B { int b; }
    public class Test
        public static void fun(String c) throws InstantiationException,
            IllegalAccessException, ClassNotFoundException
            Object obj = Class.forName(c).newInstance();
            System.out.println("Object created for class:"
                            + obj.getClass().getName());
        public static void main(String[] args) throws InstantiationException,
        IllegalAccessException, ClassNotFoundException

    Class.forName() method return class object on which we are calling newInstance() method.  If the class doesn’t exist then ClassNotFoundException will occur. InstantionException will occur if the class doesn’t receive any default constructor as newInstance() method.