Wednesday, March 29, 2017

Difference new vs newInstance() in java Java High Q

New :- 

We can use new operator to create an object if we know class name at the beginning
Ex :- Test test=new Test();
Student student=new Student();
Customer customer=new Customer();


newInstance():-

We can use newInstance() method to create object it e don’t know class name at the beginning and it is available dynamically at runtime.

Ex :- 

class Student{
}
Class Customer {
}
 package com.javahighq.test;


public class Test {
      public static void main(String[] args) {
            try {
                  Object o=Class.forName(args[0]);
                  System.out.println("objcet created for"+o.getClass().getName());
            } catch (ClassNotFoundException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
            }
      }
}



new
newInstance()
    It is an operator in java

     We can use new operator to create object if we know class name at the beginning

   To use new operator class not required to contain no-augment  constructor


 At runtime if the corresponding .class file not available then  we will get runtime exception saying NoClassDefFuondError which is unchecked


   It is a method present in java.lang.Class name

    We can use newInstance() method to crate object if we don’t know class name at the beginning and it is available dynamically at runtime.

    To use newInstance() method compulsory class should contain no-augment constructor otherwise we will get runtime exception saying InstantiationException.

     At runtime it the corresponding .class file not available then we will get RuntimeException saying ClassNotFoundException which is checked

No comments:

Post a Comment