Java newInstance

Java newInstance


With Java newInstacnce() of class Class, we can create an object as you will do with new keyword.
Example on Java newInstance


Java newInstance
Output screenshot on Java newInstance Example

The newInstance() method of java.lang.Class returns an object of class Object represented by a Class object. It is very confusing. Let us see what I mean.

Student std1 = new Student();
Class cls1 = std1.getClass();
Object obj1 = cls1.newInstance();
Student std2 = (Student) obj1;

The getClass() method of Object class returns an object of Class, cls1. Here, the Class object cls1 represents a Student class object. The newInstance() method of java.lang.Class returns an object Object class, obj1. The obj1 represents an object of Student. If required, we can cast this obj1 to Student class object, as I did in the above code. These objects can be used to call the methods of Student.

System.out.println(“\nstd1 marks: ” + std1.marks); // prints 50
System.out.println(“std2 marks: ” + std2.marks); // prints 0

The Student objects std1 and std2 are very different. They maintain encapsulation. For this reason, std2.marks prints 0 (the default value of marks) and not 50 of std1 marks.

The newInstance() method throws two checked exceptionsInstantiationException and IllegalAccessException.

Class cls2 = Class.forName(“Student”);
Object obj2 = cls2.newInstance();

There is another way of getting Class object. It is by using forName() method of Class as in the above code.

The forName() method throws ClassNotFoundException.

Let us see what we can do more with Class object.

Leave a Reply

Your email address will not be published. Required fields are marked *