new operator vs newInstance() method

Total Post:113

Points:791
Java  Class 
 174  View(s)
Ratings:
Rate this:

new operator vs newInstance() method in Java ?


  1. Post:140

    Points:984
    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
        {
             fun("A");
        }
    }

    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. 

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!