Home » Java programming language

Java Class class newInstance() method with example

Class class newInstance() method: Here, we are going to learn about the newInstance() method of Class class with its syntax and example.
Submitted by Preeti Jain, on November 16, 2019

Class class newInstance() method

  • newInstance() method is available in java.lang package.
  • newInstance() method is used to create a new instance of the class denoted by this Class object.
  • newInstance() method is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.
  • newInstance() method does not throw various exceptions at the time creating a new instance of the class.
    • IllegalAccessException: This exception may raise when this Class or its constructor is not accessible.
    • InstantiationException: This exception may raise when class instantiation fails.
    • ExceptionInInitializerError: This exception may raise when the initialization stimulated by the method fails.
    • SecurityException: This exception may raise when the security manager exists.

Syntax:

    public Object  newInstance();

Parameter(s):

  • It does not accept any parameter.

Return value:

The return type of this method is Object, it returns a new instance of the class.

Example:

// Java program to demonstrate the example 
// of Object newInstance () method of Class 

public class NewInstanceOfClass {
    public static void main(String[] args) throws Exception {
        // Create and Return String class
        StringBuilder s1 = new StringBuilder();
        Class cl1 = s1.getClass();

        // We are creating a new instance of the
        // class denoted by this object cl1
        // by using newInstance() method
        Object s2 = cl1.newInstance();
        Class cl2 = s2.getClass();

        // Display Instance
        System.out.println("Instance s1: " + cl1.toString());
        System.out.println("Instance s2: " + cl2.toString());
    }
}

Output

Instance s1: class java.lang.StringBuilder
Instance s2: class java.lang.StringBuilder


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.