Sunday 27 May 2018

When is InstantiationException thrown?

This exception thrown, when you try to create an object by using 'newInstance' method of java.lang.Class, but the object creation to that class is not possible.

The creation of the new object can fail, because of below reasons.
a.   When you try to create an object for an abstract class, interface, array, to a primitive type (or) void.

b.   When the class do not have default constructor.

Employee.java

package com.sample.model;

public abstract class Employee {

 private int id;
 private String name;

 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 @Override
 public String toString() {
  return "Employee [id=" + id + ", name=" + name + "]";
 }

}

Test.java

package com.sample.test;

import com.sample.model.Employee;

public class Test {

 public static void main(String args[]) throws InstantiationException, IllegalAccessException {
  Class<Employee> clazz = Employee.class;

  Employee emp = clazz.newInstance();

 }
}


I defined ‘Employee’ as an abstract class. When I try to create an object to the Employee class, I got ‘InstantiationException’.

Exception in thread "main" java.lang.InstantiationException
         at sun.reflect.InstantiationExceptionConstructorAccessorImpl.newInstance(InstantiationExceptionConstructorAccessorImpl.java:48)
         at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
         at java.lang.Class.newInstance(Class.java:442)
         at com.sample.test.Test.main(Test.java:10)


Previous                                                 Next                                                 Home

No comments:

Post a Comment