Creating object without new Keyword

Creating object without new Keyword

Creating an object of a Class without using new Keyword

It is of general practice to create an object with new keyword. It is also possible to create an object without new keyword. This is of logical significance only and not used in regular practice.


Creating object without new Keyword
Output screenshot of Creating object without new Keyword

Class c1 = Class.forName(“Hello”);
Object obj1 = c1.newInstance( );

forName() is a static method of java.lang.Class that loads the .class file of Hello into the RAM and returns the Hello as an object of class Class. c1 contains the reference of Hello. newInstance() method of class Class returns an object of Object class. Now, obj1 contains the reference of Hello. Internally, JVM may use new keyword.

Hello h1 = (Hello) obj1;

The object obj1 is explicitly type casted to Hello object, h1. It is a long process.

Total there are 5 styles of creating an object in Java without new keyword. This is one. Would you like to know the other 4 styles also.

11 thoughts on “Creating object without new Keyword

  1. prateek

    hi,
    i have understood that how the implicit casting works.
    but, i am confused with the explicit casting. can you please explaing?
    for eg:
    A is a super class and B is a subclass and class B contains the mettod b1. Please see below:
    A a=new B();
    a.b1();// why does this statement throws an error?
    and if i do like:
    B b=(B)a;
    a.b1();// why this statement doesn’t throw the error?

  2. prasanna

    hello

    i have written this code

    package exp;
    import java.lang.*;
    public class F1
    {
    static int power=100;

    public static void main(String args[]) throws ClassNotFoundException, InstantiationException, IllegalAccessException
    {
    System.out.println(“Hello World”);
    System.out.println(“Best wishes”);
    // System.out.println(“Speed of the car is “+power+”Kmph”);
    Class c1=Class.forName(“F1”);
    Object ob1=c1.newInstance();
    F1 ferrari=(F1)ob1;
    System.out.println(“speed of ferrari is”+ferrari.power+”Kmph”);

    }
    }

    i am not getting the output .can u please let me know where i went wrong

          1. Mahendar

            Hi Vinay/Prathak,

            Probably you are not giving the fully qualified name of the class(I mean, complete class name with package) in Class.forName(…) method. Check once.

            Thanks,
            Mahendar

Leave a Reply

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