new Operator vs newInstance() Method in Java
In Java, new is an operator where newInstance() is a method where both are used for object creation. If we know the type of object to be created then we can use a new operator but if we do not know the type of object to be created in beginning and is passed at runtime, in that case, the newInstance() method is used.
In general, the new operator is used to create objects, but if we want to decide the type of object to be created at runtime, there is no way we can use new operator. In this case, we have to use the newInstance() method.
Let us discuss the new operator. In Java, object creation takes place in 3 steps as listed: object instantiation and object initialization, and constructor invocation.
As we will use the new keyword, the compiler interprets the variable as an object
Datatype object = new Constructor();
[1, 4, 3]
Note: We can use it with constructor too where we wanted to call object not variables.
Now if we come up with to newInstance() method which is present inside java.lang package inside Class class. As we already discussed it is used where we load the class from remote sources.
Consider a scenario where we connect to the database later using our java program for execution. It can be more evidently explained with the JDBC example. Remember there we used the Class.forName() method to load registers dynamically and there we used newInstance() method on top of it to create objects dynamically.
Output Explanation: forName() method returns the class ‘Class’ object on which we are calling newInstance() method which will return the object of that class that we are passing as a command-line argument.
- If the passed class doesn’t exist then ClassNotFoundException will occur.
- InstantionException will occur if the passed class doesn’t contain the default constructor as newInstance() method internally calls the default constructor of that particular class.
- IllegalAccessException will occur if we don’t have access to the definition of the specified class definition.
Related Article: Reflection in Java
This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Please Login to comment...